max pleaner max pleaner - 5 months ago 14
Node.js Question

in Node REPL, Side effects in promise are run when function is defined, not when it is invoked

This is a behavior of Promises that I didn't anticipate.

I'm getting the hang of promises' asynchronous nature and am creating sequences of promises for control flow. However, I'm worried my control flow's synchronicity is not being respected.

In the following example, it seems like a Promise's side effects are being called when the Promise is defined, not when it's run. By "side effects", I specifically mean

console.log
in this example, but in my app I'm also doing a bit of global configuration from within my Promise resolvers.

In this example, I am running a
nodejs
REPL with
v5.11.2
, a relatively recent version.

> testFn = new Promise(function(resolve, reject){
console.log("called when promise defined");
resolve("called when promise invoked")
})
called when promise defined
Promise { 'called when promise invoked' }
> testFn.then(function(res){console.log(res)})
Promise { <pending> }
> called when promise invoked


Are promises'
resolve
or
reject
values calculated before the function is invoked? It would seem so in this REPL example. I would have expected the
called when promise defined
string to also be logged when
testFn.then
is called.

Answer

The new Promise() constructor takes a function that is invoked immediately to provide the initial value of the promise (typically asynchronously).

Calling then() after that just consumes that value once it's ready; it doesn't invoke anything.

Comments