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
Promise.resolve would be resolved straight away (syncroniously), while setImmediate explicitly straight after the execution of current event.
I'm not going to answer the bolded part about technicalities, but only the question
Which should I use?
I don't think there is any reason to use Promise.resolve().then()
unless you are interested in the promise for the result of your asynchronously executed function. Of course, if you are, then this would be far superior than dealing with callback hell or making a new Promise
from setTimeout
or nextTick
.
There's also a second technical difference, more import than the timing: promises do swallow exceptions. Which you probably don't want. So, like @vkurchatkin mentioned, don't create promises only to throw them away. Not only because it's slower, but because it makes your code less readable and your app more error-prone.
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.