Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.resolve().then vs setImmediate vs nextTick

NodeJS 0.11 as well as io.js and the Node 0.12 branch all ship with native promises.

Native promises have a .then method which always executes on a future event loop cycle.

So far I've been using setImmediate to queue things to the next iteration of the event loop ever since I switched from nextTick:

setImmediate(deferThisToNextTick); // My NodeJS 0.10 code process.nextTick(deferThisToNextTick); // My NodeJS 0.8 code 

Since we now have a new way to do this:

Promise.resolve().then(deferThisToNextTick);  

Which should I use? Also - does Promise.resolve.then act like setImmediate or like nextTick with regards to code running before or after the event loop?

like image 251
Benjamin Gruenbaum Avatar asked Dec 25 '14 13:12

Benjamin Gruenbaum


People also ask

What is the difference between process nextTick () and setImmediate ()?

process. nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop. setImmediate() method is used to execute a function right after the current event loop finishes.

What is promise resolve () then?

resolve() The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

When should I use nextTick?

Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.

What is the difference between setImmediate () and setTimeout ()?

setImmediate() vs setTimeout()setImmediate() is designed to execute a script once the current poll phase completes. setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.


1 Answers

Using Promise.resolve().then has no advantages over nextTick. It runs on the same queue, but have slightly higher priority, that is, promise handler can prevent next tick callback from ever running, the opposite is not possible. This behaviour is an implementation detail and should not be relied on.

Promise.resolve().then is obviously slower (a lot, I think), because it creates two promises which will be thrown away.

You can find extensive implementation info here: https://github.com/joyent/node/pull/8325

The most important part: Promise.resolve().then is like nextTick and not like setImmediate. Using it n place of setImmediate can change your code behaviour drastically.

like image 186
vkurchatkin Avatar answered Sep 22 '22 02:09

vkurchatkin