Search code examples
javascriptloopspromisebluebird

Force continuation of BlueBird Promise.each if an item in the iterable causes a reject


So we would like to execute a list of promises in serial, but continue on reject. In this example below, we have control over the reject, but in the use case we will not have control over reject as it is coming from Mongoose.

let Promise = require('bluebird');
let arr = [1,2,'a',4,5];

Promise.each(arr, function(item) {
        return new Promise((resolve, reject) => {
            if (typeof item === 'number') {
                console.log(item);
                resolve(item);
            } else {
                reject(new Error('item not number'));
            }
        });
    })
    .then(res => { console.log(res) })
    .catch(err => {console.log('error ' + err.message)});

Which yields:

1

2

error item not number

As you can see it quit when it hit the string in the array. Is there any way to make it continue to the end of the array?


Solution

  • If you don't have any control over the resolution of the promise, you can easily gain it by handling the rejections before each sees them:

    Promise.mapSeries(arr, function(item) {
        return somethingThatMightReject()
        .catch(function(err) {
            // ignore it? Log it?
            return /*reasonable result*/; // continue anyway
        });
    })
    

    (in case of Promise.each not mapSeries, you don't have to return a meaningful result but just have to swallow the error)