MDN documentation states that
When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.
Therefore, what am I doing wrong, considering that await
expects a resolved promise?
foo();
async function foo(){
await bar();
zoo();
}
async function bar(){
setTimeout(() => {
console.log("bar");
return;
}, 1000);
}
function zoo(){
console.log("zoo");
}
According to what I (wrongly) understood, it should first log bar
and then zoo
, but it's logging the other way around.
EDIT: Now, thanks to clarifications from @Matt Morgan, I understand the mistake, as the bar()
function returns undefined
. Nonetheless, I thought that by calling an async
function per se alone would make the function return immediately an unresolved promise and that such promise would be resolved when the async
function would return any value (even undefined). But I now realise one really needs to return a promise oneself by declaring it with return Promise
statement. I think the MDN article for async
, which I read it all, is a bit confusing on this topic (just my opinion).
Therefore I could simply amend my bar()
function to:
function bar(){
return new Promise(function(resolve){
setTimeout(() => {
console.log("bar");
resolve();
}, 1000);
});
}