Obviously, given a list l
and an function f
that returns a promise, I could do this:
Promise.all(l.map(f));
The hard part is, I need to map each element, in order. That is, the mapping of the first element must be resolved before the the next one is even started. I want to prevent any parallelism.
I have an idea how to do this, which I will give as an answer, but I am not sure it's a good answer.
Edit: some people are under the impression that since Javascript is itself single-threaded, parallelism is not possible in Javascript.
Consider the following code:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
mapAsync([3000, 2000, 1000], delay).then(n => console.log('beep: ' + n));
A naïve implementation of mapAsync()
would cause "beep" to be printed out once a second for three seconds -- with the numbers in ascending order -- but a correct one would space the beeps out increasingly over six seconds, with the number in descending orders.
For a more practical example, imagine a function that invoked fetch()
and was called on an array of thousands of elements.
Further Edit:
Somebody didn't believe me, so here is the Fiddle.