skip to Main Content

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


    1. then and catch create new promises.
    2. you await the catch’s promise.
    3. since your initial promise is resolved, then’s callback is executed and the then’s and catch’s promises are resolved in a chain
    4. then console.log() is executed after await
    Login or Signup to reply.
  1. after 5 seconds the async function will resume the part written after await keyword by calling it to call stack. that part will encounter .then method first which will be call immediately as the promise is already fulfilled

    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 is awaited. Your code is equivalent to

    async function test(){
        console.log("start");
        console.log("going on...");
        const _p1 = new Promise((resolve, reject) => {setTimeout(() => resolve("promise value"), 5000);});
        const _p2 = _p1.then((result) => console.log(result));
        const _p3 = _p2.catch((error) => console.log(error));
        await _p3;
        console.log("still going on...");
    }
    

    and not doing

    async function test(){
        console.log("start");
        console.log("going on...");
        const _p1 = new Promise((resolve, reject) => {setTimeout(() => resolve("promise value"), 5000);});
        await _p1;
        const _p2 = _p1.then((result) => console.log(result));
        const _p3 = _p2.catch((error) => console.log(error));
        console.log("still going on...");
    }
    

    (which would behave as described in your comment, and log "promise value" after "still going on")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search