Friday 21 April 2017

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

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



via Marco Galassi

No comments:

Post a Comment