Skip to content

Instantly share code, notes, and snippets.

@dimabory
Created March 5, 2019 15:31
Show Gist options
  • Save dimabory/eaf3fbfc7b50608b364ddc687ce284f3 to your computer and use it in GitHub Desktop.
Save dimabory/eaf3fbfc7b50608b364ddc687ce284f3 to your computer and use it in GitHub Desktop.
Explaining Microtasks and Macrotasks in Node
console.log('script start')
const interval = setInterval(() => {
console.log('setInterval')
}, 0)
setTimeout(() => {
console.log('setTimeout 1')
Promise.resolve().then(() => {
console.log('promise 3')
}).then(() => {
console.log('promise 4')
}).then(() => {
setTimeout(() => {
console.log('setTimeout 2')
Promise.resolve().then(() => {
console.log('promise 5')
}).then(() => {
console.log('promise 6')
}).then(() => {
clearInterval(interval)
})
}, 0)
})
}, 0)
Promise.resolve().then(() => {
console.log('promise 1')
}).then(() => {
console.log('promise 2')
})
@dimabory
Copy link
Author

dimabory commented Mar 5, 2019

script start
promise1
promise2
setInterval
setTimeout1
promise3
promise4
setInterval
setTimeout2
setInterval
promise5
promise6

@dimabory
Copy link
Author

dimabory commented Mar 5, 2019

Why use process.nextTick()?

There are two main reasons:

  • Allow users to handle errors, cleanup any then unneeded resources, or perhaps try the request again before the event loop continues.

  • At times it's necessary to allow a callback to run after the call stack has unwound but before the event loop continues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment