In this code, callback function of .then
is executed before the console.log("still going on...")
but normally callback function of .then
shall be posted to micro stack first before coming to call stack.
What is happening differently here and why?
async function test(){
console.log("start");
console.log("going on...");
await new Promise((resolve, reject) => {setTimeout(() => resolve("promise value"), 5000);})
.then((result) => console.log(result))
.catch((error) => console.log(error));
console.log("still going on...");
}
test();
console.log("end.");
Output:
start
going on...
end.
promise value
still going on...
2
Answers
then
andcatch
create new promises.console.log()
is executed afterawait
No. The
.then()
and.catch()
methods will already have been called before the async function is resumed, in fact they have created the promise that isawait
ed. Your code is equivalent toand not doing
(which would behave as described in your comment, and log "promise value" after "still going on")