Skip to content

Instantly share code, notes, and snippets.

@brannondorsey
Created June 10, 2018 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brannondorsey/debe4870bfdf86de4f48639cb4b3768a to your computer and use it in GitHub Desktop.
Save brannondorsey/debe4870bfdf86de4f48639cb4b3768a to your computer and use it in GitHub Desktop.
Does the Node event loop maintain the order async callbacks are sent to it?
// test if node's event loop is gauranteed to run events in the order they are
// pushed to the event queue. Turns out they DO NOT!!! 10,000 integers appended
// one after the other to append.txt using fs.appendFile() will NOT maintain
// the order of those ints.
const fs = require('fs')
function getAppend(i) {
return () => {
fs.appendFile('append.txt', `${i.toString().padStart(3)}\n`, (err) => {
if (err) throw err
console.log(i)
})
}
}
for (let i = 0; i < 10000; i++) {
getAppend(i)()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment