Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active June 10, 2018 18:48
Show Gist options
  • Save shuhei/34efae93e288ebf20a46de633a53ae9d to your computer and use it in GitHub Desktop.
Save shuhei/34efae93e288ebf20a46de633a53ae9d to your computer and use it in GitHub Desktop.
Execution of Promise Chain in Node.js

Execution of Promise Chain in Node.js

After reading The Node.js Event Loop, Timers, and process.nextTick()...

Q. I write a lot of promise chains in applications. How is a promise chain executed? Is it performant?

The experiment shows:

  • Chained promises are eagerly executed before proceeding to the next phase.
  • Promise chaining is a bit slower than synchronous execution, but not too much.
  • (Also, chained process.nextTick() are eagerly executed before proceeding to the next phase.)
setTimeout(() => {
process.nextTick(() => {
console.log('nextTick 0');
console.time('nextTick 1');
process.nextTick(() => {
console.timeEnd('nextTick 1');
console.time('nextTick 2');
process.nextTick(() => {
console.timeEnd('nextTick 2');
});
});
});
setImmediate(() => {
console.log('setImmediate');
});
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve(1)
.then((n) => {
console.log('Promise 0');
console.time('Promise 1');
return n + 1;
})
.then((n) => {
console.timeEnd('Promise 1');
console.time('Promise 2');
return Promise.resolve(n + 1);
})
.then((n) => {
console.timeEnd('Promise 2');
console.time('Promise 3');
return Promise.resolve(n + 1);
})
.then((n) => {
console.timeEnd('Promise 3');
});
console.time('sync 0');
const n = 1;
console.timeEnd('sync 0');
console.time('sync 1');
const nn = n + 1;
console.timeEnd('sync 1');
console.time('sync 2');
const nnn = nn + 1;
console.timeEnd('sync 2');
});
$ node -v
v10.4.0
$ node index.js
sync 0: 0.146ms
sync 1: 0.004ms
sync 2: 0.004ms
nextTick 0
nextTick 1: 0.387ms
nextTick 2: 0.031ms
Promise 0
Promise 1: 0.029ms
Promise 2: 0.025ms
Promise 3: 0.018ms
setImmediate
setTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment