Why does this chain of promises solve immediately?

Can someone explain to me why the final promise ( d ) from the code below is immediately resolved?

 //promises that are never resolved nor rejected var a = new Promise(function(r,re){}); var b = new Promise(function(r,re){}); var c = new Promise(function(r,re){}); var d = [a, b, c].reduce(function (previousPromise, promise) { return previousPromise.then(promise); }, Promise.resolve()); 

I create an array of promises that waits forever, so the promise received must also be kept forever, as it waits for all subsequent promises to complete ( as presented here ). I used promises for a while, but I obviously missed something.

Chrome DevTools - promises executed code

+7
javascript promise ecmascript-6 es6-promise
source share
2 answers

then does not accept a Promise as input, it accepts 2 functions, 1 for execution and 1 for rejection.

Reason d resolved due to the fact that the call. then with a non-convertible value (even a numeric literal - 1 or undefined ) forces you to replace the onFulfilled function with "Identity", which simply repeats the execution of any value that was allowed in the previous step. See PerformPromiseThen

Try it like this:

 //promises that are never resolved nor rejected var a = function() { return new Promise(function(r,re){}); }; var b = function() { return new Promise(function(r,re){}); }; var c = function() { return new Promise(function(r,re){}); }; // or simply, a = b = c after setting the function for c var d = [a, b, c].reduce(function (previousPromise, fn) { return previousPromise.then(fn, /* not passing a rejection handler... */); }, Promise.resolve()); 

Or alternatively ...

 //promises that are never resolved nor rejected var a = new Promise(function(r,re){}); var b = new Promise(function(r,re){}); var c = new Promise(function(r,re){}); var d = [a, b, c].reduce(function (previousPromise, promise) { return previousPromise.then(function() {return promise;}); }, Promise.resolve()); 

And since you are using promises and ES6, you can be more concise:

 let a = new Promise(() => {}); let b = new Promise(() => {}); let c = new Promise(() => {}); let d = [a, b, c].reduce((previousPromise, promise) => previousPromise.then(() => promise), Promise.resolve()); 
+11
source share
 var d = [a, b, c].reduce(function (previousPromise, promise) { return previousPromise.then(promise); }, Promise.resolve()); 

Your initial promise state is allowed, you set it as Promise.resolve (). Check the documentation for the abbreviation https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

-one
source share

All Articles