Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

javascript - Using async await on custom promise

Im trying to use async await on a function that returns a promise but the out put im getting is Promise { <pending> }. In here im using function called convertFiletoPDF which returns a promise. I need to get the output (the path that i have mention in resolve() ). When i use it as

convertFiletoPDF(file).then((result) => {
  console.log(result);
}).catch((err)=>{
  console.log(err);
});

it gives the expected result.Whats wrong with the code below? im quite new to these async await and promises.

 function convertFiletoPDF(file) {
  return new Promise(function(resolve, reject) {
    unoconv.convert(file, "pdf", function(
      err,
      result
    ) {
      if (err) {
        reject(err);
      }
      let File = file.substring(file.lastIndexOf("/")+1,file.lastIndexOf("."));
      // result is returned as a Buffer
      fs.writeFile(__dirname+"/files/converted/"+File+".pdf", result, error => {
        /* handle error */
        if (err) reject(error);
        else resolve("./files/converted/"+File+".pdf");
      });
    });
  });
}

async function myfunc(file){
  let res = await convertFiletoPDF(file);
  return res;
}

let res = myfunc(file);
console.log(res);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The return value of an async function is a promise, so naturally that's what your console.log outputs. You need to either consume the result via await (within another async function) or use then/catch (within another async function).

This is what you're currently doing:

function convertFiletoPDF(file) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, 400, "Done");
  });
}

async function myfunc(file){
  let res = await convertFiletoPDF(file);
  return res;
}

let res = myfunc("some file");
console.log(res);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...