SOUMYA SANKAR DAS
SOUMYA SANKAR DAS

Reputation: 11

Explain the output of the following code by describing the micro task queue and call stack architecture

This is the code:

function SSD() {
    console.log('SSD')
}

async function createData() {
    let status = undefined
    try {
        const res = await fetch('https://api.github.com/users/Soumya-0x000')
        status = res.status
    } catch (error) {
        console.error('error')
    }
    return status
}  //Micro task queue has high priority

setTimeout(() => {
    console.log(!undefined)
}, 1000);    //callback queue / task queue has low priority

SSD()

createData().then((code) => {
    console.log('Status code: ', code)
})

console.log('C')

Promise.resolve().then(() => console.log('D'))    //Micro task queue has high priority

console.log('E')

I thought output should look like:

SSD
C
E
Status code:  200
D
true

But actual output is:

SSD
C
E
D
Status code:  200
true

API is ok. Now please someone explain me, why and how 'D' is printed before 'Status code: 200' is printed.

I'm expecting the output to be:

SSD
C
E
Status code:  200
D
true

Because createData() is queued first inside micro task queue then it will come to the resolved promise. It is true that synchronous tasks are performed first and Promise is synchronous. But createData() comes first in micro task queue so it should be resolved first and Status code: 200 should be printed first then D. But this is not happening. Please explain........

Upvotes: 1

Views: 59

Answers (1)

Yousaf
Yousaf

Reputation: 29282

But createData() comes first in micro task queue so it should be resolved first and Status code: 200 should be printed first then D

The callback function of createData().then(...) will be enqueued in the microtask queue only when the promise returned by the createData function is resolved. Until then, it is just registered as a fulfillment handler.

After the synchronous execution of your script ends, you have three promises:

  • First one returned by fetch call
  • Second one in pending state, returned by async createData function, and
  • Third in resolved state returned by Promise.resolve().

Second promise is dependent on the first promise and will only resolve once the first one resolves. On the other hand, the third promise is already resolved, as a result, its fulfillment handler is enqueued in the microtask queue first.

Upvotes: 0

Related Questions