Reducing or loop / recursion chaining comes to mind as a common practice however if you would like to keep and access to the intermediate resolutions here i have another approach by using an invention of Haskell's scanl
function in JS.
scanl
is similar to JS .reduce()
but like .map()
always returns a same size array holding the interim values. So the scanl
function would look something like;
var scanl = (xs, f, acc) => xs.map((a => e => a = f(a,e))(acc));
So if you do;
scanl([1,2,3,4], (a,e) => a + e, 0) // -> [1,3,6,10]
So having scanl
at hand now we may attempt to sequence promises by keeping the intermetiate resolutions in a resulting array.
var scanl = (xs, f, acc) => xs.map((a => e => a = f(a,e))(acc)),
proms = Array(5).fill().map((_,i) => new Promise((v,x) => setTimeout(v,100+Math.random()*1900,`res ${i+1}`)));
proms = scanl(proms, (a,p,t) => a.then(v => (t = v, p))
.then(v => `${t} and ${v}`)
.then(s => (console.log(`did stg with ${s}`),s)), Promise.resolve("init 0"));
Promise.all(proms)
.then(vs => vs.forEach(v => console.log(v)));
.as-console-wrapper {
max-height : 100% !important
}
Of course above function is just makeshift. I use an unused t
argument as a temporary variable defined in the callbacks context.