How can I dynamically create a series of promises and have them execute in sequence?
pseudocode
for x=0 to maxValue
promiseArray.push(createNewPromise(x))
executeAllPromisesSequentially(promiseArray)
where
executeAllPromisesSequentially is functionally equivalent to
promise1()
.then(promise2)
.then(promise3)
etc
...
There are some patterns displayed on my gist
Promise Iteration with Reduce
let tasks = [ /* ... */ ]
let promise = tasks.reduce((prev, task) => {
return prev.then(() => {
return task();
});
}, Promise.resolve());
promise.then(() => {
//All tasks completed
});
Sequential Iteration Pattern
let tasks = [ /* ... */ ]
let promise = Promise.resolve();
tasks.forEach(task => {
promise = promise.then(() => {
return task();
});
});
promise.then(() => {
//All tasks completed
});
Sequential Iteration Example
function spiderLinks(currentUrl, body, nesting) {
let promise = Promise.resolve();
if(nesting === 0) {
return promise;
}
const links = utilities.getPageLinks(currentUrl, body);
links.forEach(link => {
promise = promise.then(() => spider(link, nesting - 1));
});
return promise;
}
Just build up a chain as jaromandaX said. However you need to make sure that you use let
inside the loop to closure the x:
let chain = Promise.resolve();
const promises = [];
for(let x = 0; x < maxValue; x++)
promises.push(chain = chain.then(() => createNewPromise(x)));
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.