max pleaner max pleaner - 1 year ago 80
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

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
REPL with
, 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'
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
is called.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download