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:
- 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?
tldr I must run multiple independent functions in a single express route and I don't know how to handle possible errors
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