Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of execution for asynchronous tasks in JavaScript: Promise and setTimeout

function job(){
    sequenceB()
    sequenceC()
}

function sequenceB(){
    setTimeout(_ => console.log(`πŸ… Timeout at B`), 0);
    Promise.resolve().then(_ => console.log('🍍 Promise at B'));
}

function sequenceC(){
    setTimeout(_ => console.log(`πŸ… Timeout at C`), 0);
    Promise.resolve().then(_ => setTimeout(console.log('🍍 Promise at C'), 1000));
}
job();

what will be the print order here and why? I seem to get the output in this order 🍍 Promise at B, 🍍 Promise at C, πŸ… Timeout at B, πŸ… Timeout at C

tested this on both chrome(latest version) and edge(latest version)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you call job(), sequenceB() is called, then sequenceC() is called. When sequenceB() runs setTimeout(_ => console.log('πŸ… Timeout at B'), 0); will be pushed to the callback queue and Promise.resolve().then(_ => console.log('🍍 Promise at B')); will be pushed to the job queue. Then the execution starts for sequenceC(). The same happens again, setTimeout(_ => console.log('πŸ… Timeout at C'), 0); is pushed to the callback queue and Promise.resolve().then(_ => setTimeout(console.log('🍍 Promise at C'), 1000)); is pushed to the job queue.

Now the event loop says hey, is the job/microtask empty? And it’s not, so that code gets executed, which is the promise from the sequenceB() function, then it checks the job queue again, and it finds the other promise.

The next time around, it looks and the job/microtask queue is empty so then it looks at the callback queue and there is your setTimeout callback, so that gets pushed to the call stack. Once that executes, the event looks again and sure enough there is another setTimeout callback there. This is again executed and the process repeats.

With that being said the output is:

// from the microtask queue
🍍 Promise at B
🍍 Promise at C

// from the callback queue
πŸ… Timeout at B
πŸ… Timeout at C
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading