Facebook Pixel

What is the order of execution in the Node.js event loop?

Sync code runs first, then process.nextTick callbacks, then promise microtasks, then macrotasks (timers, I/O callbacks, setImmediate). Microtasks always run before the next macrotask, which is the key rule.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Node.js Event Loop Order of Execution Explained With Code

Because promises are microtasks, which run after the current operation but before the next macrotask. setTimeout is a macrotask. So in console.log('1'); setTimeout(fn); promise.then(fn); console.log('4'), the order is 1, 4, then the promise, then setTimeout.

process.nextTick callbacks. They run before promise microtasks, both before macrotasks. So console.log('1'); nextTick(fn); promise.then(fn) outputs 1, nextTick, promise. This is a Node.js-specific behavior.

Because if you do not understand the order, you cannot predict when async code runs, which causes bugs and confusion. The order is deterministic: sync, nextTick, promises, then macrotasks. Understanding it is essential for debugging timing bugs.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.