Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve Web3 promises objects? [duplicate]

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);
like image 876
TRomesh Avatar asked Aug 12 '26 11:08

TRomesh


1 Answers

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 at the top level of a module) or use then/catch.

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);

You need to be doing either this:

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

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

// (In a module you wouldn't need this wrapper)
(async() => {
    try {
        let res = await myfunc("some file");
        console.log(res);
    } catch (e) {
        // Deal with the fact there was an error
    }
})();

or with then and catch:

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

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

myfunc("some file")
    .then(res => {
        console.log(res);
    })
    .catch(e => {
        // Deal with the fact there was an error
    });
like image 80
T.J. Crowder Avatar answered Aug 14 '26 12:08

T.J. Crowder