I'm trying to understand the following 2 sample functions using async-await and promise.
I expect both functions to return "output", but the function using promise returns an undefined instead.
Why is that the case? I'm already returning the value in promise.resolve().then() but there's no value returned after all.
I encountered this problem while working on my project. I was using the promise approach to return a value but there's no value returned. I then solved it using async-await, but I couldn't understand why?
async function asyncFunction(input) {
try {
let output = await Promise.resolve("output");
return output;
} catch (err) {
console.log(err);
}
}
function promiseFunction(input) {
Promise.resolve().then(function() {
return "output";
}).catch(function(err){
console.log(err);
})
}
async function run() {
let a = await asyncFunction();
let b = await promiseFunction();
console.log("async function output: " + a); //async function output: output
console.log("promise function output: " + b); //promise function output: undefined
}
run();
I expect both asyncFunction() and promiseFunction() to return the value "output", but promiseFunction returns undefined instead.
promiseFunction
– Daniel A. White