Monday, 25 July 2016

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 { }. 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);

Answer



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





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

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




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...