Facebook Pixel

What are microtasks vs macrotasks in Node.js?

Microtasks are promise callbacks and process.nextTick, which run after the current operation and before the next macrotask. Macrotasks are setTimeout, setInterval, setImmediate, and I/O callbacks, which run one per event loop phase.

Verify This Answer

Cross-check this information using these trusted sources:

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

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.

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.

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.