How to synchronize a sequence of promises?

后端 未结 6 806
醉梦人生
醉梦人生 2020-11-22 09:05

I have an array of promise objects that must be resolved in the same sequence in which they are listed in the array, i.e. we cannot attempt resolving an element till the pre

6条回答
  •  情深已故
    2020-11-22 10:06

    Although quite dense, here's another solution that will iterate a promise-returning function over an array of values and resolve with an array of results:

    function processArray(arr, fn) {
        return arr.reduce(
            (p, v) => p.then((a) => fn(v).then(r => a.concat([r]))),
            Promise.resolve([])
        );
    }
    

    Usage:

    const numbers = [0, 4, 20, 100];
    const multiplyBy3 = (x) => new Promise(res => res(x * 3));
    
    // Prints [ 0, 12, 60, 300 ]
    processArray(numbers, multiplyBy3).then(console.log);
    

    Note that, because we're reducing from one promise to the next, each item is processed in series.

    It's functionally equivalent to the "Iteration with .reduce() that Resolves With Array" solution from @jfriend00 but a bit neater.

提交回复
热议问题