• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

이 코드좀 봐주실수 있나요... 왜 에러가 났는지 모르겠네요 ..

19.07.12 05:35 작성 조회수 2.18k

0

const util = require('util')
fs.readFile('./text.txt', (err,data) => {
if(err){
throw err;
}
console.log("_______________________________________________________________________________________________________________________");
console.log(" promisefy 시작");
console.log("1 번 ",data.toString());

}
)
const num1 = util.promisify(fs.readFile);

fs.readFile('./text.txt', (err,data) => {
if(err){
throw err;
}
console.log("2 번 ",data.toString());

})
const num2 = util.promisify(fs.readFile)

fs.readFile('./text.txt', (err,data) => {
if(err){
throw err;
}
console.log("3 번 ",data.toString());
console.log("끝");
console.log("_______________________________________________________________________________________________________________________");
 

})

const num3 = util.promisify(fs.readFile)


num1()
.then ((msg) =>{
console.log(msg)
return num2()
})
.then((msg)=>
{
console.log(msg)
return num3()
})
.then((msg)=>
{
console.log(msg)
 
})
.catch((err)=>{
console.log(err)
})

async function z4() {
try{
console.log('async 시작!!!')
const fs1 = await num1()
console.log(fs1)
const fs2 = await num2()
console.log(fs2)
const fs3 = await num3()
console.log(fs3)
}catch(err){
console.error(err)
}

}
z4()

 

promisify로  잘 작동은 하는데요 ..

 

문제는 async 을 돌리면 에러가 뜨더라구요 

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined

 

뜨는데 왜그런지 잘 모르겠네요... 

도와주시면 감사하겠습니다... 

 

답변 3

·

답변을 작성해보세요.

0

모든 함수를 다 promisify에 넣을순 있습니다. 하지만 인수로 (err, result) 함수를 넣는 fs.readFile같은 것만 제대로 동작합니다.

const readFile = util.promisify(fs.readFile) 이 맞습니다.

 

readFile(경로).then

0

D_One님의 프로필

D_One

질문자

2019.07.12

감사합니다, 

 

제 코드에 문제가 있는거 같은데요 

 

const util = require('util')
fs.readFile('./text.txt', (err,data) => {
if(err){
throw err;
}
console.log("_______________________________________________________________________________________________________________________");
console.log(" promisefy 시작");
console.log("1 번 ",data.toString());

}
)
const num1 = util.promisify(fs.readFile);

 

이 부분이요, fs.readFile을 실행하면 console.log 도 찍혀서 , 

const a = fs.readFile('./text.txt', (err,data) => {
if(err){
throw err;
}
console.log("_______________________________________________________________________________________________________________________");
console.log(" promisefy 시작");
console.log("1 번 ",data.toString());

}
)

이런식으로 a 를 넣어도, console 자제차 실행이 되더라구요

const num1 = util.promisify(a);

그리고 이런식으로 정의하니까 에러가 나기도 하구요... 

혹시 어떻게하면 깔끔하게 할 수 있는지 알 수있는지 있으시간요,.? 

0

num1, num2, num3에 파일 경로 넣어주셔야 합니다. './text.js'같은 거요