I have a very basic question:
This code
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
gives this output, which is correct:
> "calling"
> "resolved"
This one however:
async function resolveAfter2Seconds() {
setTimeout(() => {
return 'resolved';
}, 2000);
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
It gives instead:
> "calling"
> undefined
From javascript.info:
The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. So, async ensures that the function returns a promise, and wraps non-promises in it
So there's something I am misunderstanding, isn't the resolveAfter2Seconds returning a promise in both scenarios (the resolveAfter2Seconds in the 2nd scenario has async)? If so why the output in the 2nd scenario?