There is a code that is taken from here :
var f1 = function() { return new Promise(function(resolve) { setTimeout(function() { console.log(1); resolve(); }, 1000); }); } var f2 = function() { return new Promise(function(resolve) { setTimeout(function() { console.log(2); resolve(); }, 2000); }); } var f3 = function() { return new Promise(function(resolve) { setTimeout(function() { console.log(3); resolve(); }, 3000); }); } var seqRunner = function(deeds) { return deeds.reduce(function(p, deed) { return p.then(deed); }, Promise.resolve()); } seqRunner([f1, f2, f3]).then(function() { console.log('Done!'); });; Explain to me, please, I don’t understand at all: why and for what purpose should the seqRunner function return an empty promise?
It is clear that after all the deeds have been executed, it calls Promise.resolve() to execute the external .then with the console output command Done! . It's clear. But I thought that if I clean at the end
.then(function() { console.log('Done!'); });; Also , Promise.resolve()) , the queue will also work without errors.
God knows, I don't understand promises. Why this , Promise.resolve()) in returning the seqRunner function?
Why can not do this:
var seqRunner = function(deeds) { return deeds.reduce(function(p, deed) { return p.then(deed); }; } seqRunner([f1, f2, f3]);
, Promise.resolve());is not in thereturnfunction of theseqRunner, but is passed as the second parameter toreduce. And the second parameter for it is the initial value for the previous (first parameter,p) parameter. Thus, such a chain is obtained. The first promis is immediately resolved, so that the next one can already be "hung" on it ... Is that how I understood everything? - VostokSistersPromise.resolve(). - Dmitriy SimushevPromise.resolve()refers to another (: - VostokSisters