Learning Journal Node.js: blocking vs non-blocking

Learning Journal Node.js: blocking vs non-blocking

Table of contents

No heading

No headings in the article.

From the Node.js official docs: "Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient."

Blocking scripts require that execution happen sequentially. This is problematic for Node.js as new operations cannot be executed until the current I/O (input / output) operation finishes.

Non-blocking scripts will still require runtime to execute sequentially but frees up the Node.js server to execute the next line of code while the current I/O operation is executed. For I/O heavy scripts, this is an essential method to program.

// Blocking Code
const getUserSync = require('./src/getUserSync')

const userOne = getUserSync(1)
console.log(userOne)

const userTwo = getUserSync(2)
console.log(userTwo)

const sum = 1 + 33
console.log(sum)
// Non-blocking Code
const getUser = require('./src/getUser')

getUser(1, (user) => {
  console.log(user)
})

getUser(2, (user) => {
  console.log(user)
})

const sum = 1 + 33
console.log(sum)

In my eyes, it seems the only advantage of the blocking code pattern over the non-blocking code pattern is the cleanliness of the code. I find it easier to reason about sequentially written code. But that reasoning is drastically outweighed by the fact that the non-blocking code is ~50% faster.