Thursday 20 April 2017

Express Middleware with multiple Promises in sequence and Error Handling

Hi, 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, so 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:Is calling multiple promises in sequence an ok design somehow?If yes, how should I handle errors?If no, what is a good design pattern in this case?Cheers ;)

Submitted April 20, 2017 at 04:36PM by honestserpent

No comments:

Post a Comment