๐Ÿ’พPromise.inSeries()

JS โŸฉ async โŸฉ Promise โŸฉ chaining โŸฉ Promise.inSeries()

๐Ÿ’พ replit๏ผšPromise in series

// ๐Ÿ”ธ Promise.inSeries()
Promise.inSeries = function(promises) {

    // store results from promises 
    const results = [];
    
    // โญ start with a "trivial" Promise
    let p = Promise.resolve();

    // โญ Promise chain of arbitrary length
    for (const promise of promises) {
        p = p.then(value => {
            results.push(value);    // save resolved value
            return promise;         // return next promise
        });
    }

    // โญ return a Promise for `results`.
    return p.then(value => {
        results.push(value); // โญ save last resolved value
        results.shift();     // โญ remove value from first "trivial" promise
        return results;
    });
    
};

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

// test 1
Promise.inSeries([
    Promise.resolve(1),
    Promise.reject('error in promise #2'),
    Promise.resolve(3),
]).then(results => 
    console.log(results)
).catch(error => {
    console.log(error)        // โ›” rejected: "error in promise #2"
});

// test 2
Promise.inSeries([
    new Promise(resolve => setTimeout(resolve, 2000, 1)),
    new Promise(resolve => setTimeout(resolve, 1000, 2)),
    Promise.resolve(3),
]).then(results => 
    console.log(results)      // โœ… fulfilled: [ 1, 2, 3 ]
).catch(error => {
    console.log(error)
});

Last updated