Red Red - 2 years ago 269
Javascript Question

Un-handled rejection from promise.each

I'm trying to make multiple database queries using bluebird's Promise.each(). The part where I'm stuck is that I'm not able to handle all the rejections (if multiple promises fail). If I do the same thing using Promise.all() it works fine(It will! because in Promise.all() if 1 promise fails the result is rejected too). My question is:
How should I handle rejections in Promise.each()?

function foo(bar){
return new Promise(resolve, reject){
var query = "elect count(*) from students Where 1=1";//DELIBRATE MISTAKE
connection.query(query, function(err, result){
if(err){reject(err)}resolve(result);
})
}
}
function api(req, res){
var tasks = [];
for(var i = 0; i < 10; i++){
tasks.push(foo(bar));
}
Promise.each(tasks).catch(err=>{return err;});
res.send('message')
}


Response:
Unhandled rejection Error: ER_PARSE_ERROR

Answer Source

You're using Bluebird#each method incorrectly. This method do the following:

Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where value is the resolved value of a respective promise in the input array.

So the first parameter must be an array of promises/values, and the second is a callback which accepts three parameters: value, index, length.

Working example:

let queryAsync = Promise.promisify(connection.query, { context: connection });

function foo(bar) {
  var query = 'elect count(*) from students Where 1=1'; // DELIBRATE MISTAKE
  return queryAsync(query);
}

function api(req, res){
  var tasks = [/* TODO: fill array with taskIds or something else*/];

  Promise
    .each(tasks, task => foo(task))
    .then(() => res.send('message'))
    .catch(err => {
      console.log(err);
      res.status(500).send(err);
    });
}

In the example above I use Bluebird#promisify method to promisify callback-style connection.query function. Bluebird already presents the promisification functionality, you shouldn't create your own.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download