Consistent execution in node

Best practise

It is very important for APIs to be either 100% synchronous or 100% asynchronous.

Source: node's doc

Counter example

const isSync = Math.random() > 0.5

foo(isSync, () => {
  console.log('foo')
})
console.log('bar')


function foo(isSync, callback) {
  if (isSync) return callback()
  setTimeout(() => { return callback() }, 100)
}

Two outcomes are possible every time this code is executed.

Either:

foo
bar

Or:

bar
foo

One issue is that foo looks like an asynchronous function because of its callback argument. But every other time it will executes synchronously.

Alternative implementation

const isSync = Math.random() > 0.5

foo(isSync, () => {
  console.log('foo')
})
console.log('bar')


function foo(isSync, callback) {
  // Note the use of `process.nextTick.`
  if (isSync) return process.nextTick(callback)
  setTimeout(() => { return callback() }, 100)
}

Only one outcome is possible:

bar
foo
Mastodon