Home:ALL Converter>How to handle errors from multiple independent promises inside a single route handler in express?

How to handle errors from multiple independent promises inside a single route handler in express?

Ask Time:2017-04-21T17:24:46         Author:smellyarmpits

Json Formatter

I have an Express route handler that needs to start multiple operations asynchronously. These operations are indepentend and do not interfere with each other. I tried to do this with Promises, but I have problems when I have to handle errors from Promises.

Let me explain with an example.

router.post('/data', function (req, res, next) {
  // do something before anything else
  next();
}, function (req, res, next) {

promise1(req.params)
  .then((data) => {
    // do something with data
  }).catch((err) => {
  next(err);
  });

promise2(req.params)
  .then((data) => {
    // do something with data
  }).catch((err) => {
    next(err);
  });

}, function (err, req, res, next) {
  // error middleware
});

The problem is that if both the 2 promises incur into errors, they both end up calling next(err) in the middleware and there is a problem here.

The second call to next(err) ends up in nothing and the middleware does not handle anything.

I'm looking for suggestions on a couple of things:

  1. Is calling multiple promises in sequence an ok design somehow?
  2. If yes, how should I handle errors?
  3. If no, what is a good design pattern in this case?

tldr I must run multiple independent functions in a single express route and I don't know how to handle possible errors

Author:smellyarmpits,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/43538865/how-to-handle-errors-from-multiple-independent-promises-inside-a-single-route-ha
rsp :

You can use Promise.all like this:\n\nPromise.all([promise1(req.params), promise2(req.params)])\n .then(results => {\n // both succeeded\n // do something with results[0] and results[1]\n }).catch(err => {\n // some error happend\n next(err);\n });\n\n\nSee the docs:\n\n\nhttps://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\n\n\nSee also other answers about Promise.all for more examples.",
2017-04-21T09:51:59
yy