Reputation: 7103
I have request coming from client based on params passed i have to make two api calls so in order to achieve that i used promise.all. I am trying to figure out if we have error in 2nd promise how would you catch error on first promise ?
Also if there is any better approach to handle promises in below case please advise i am fairly new to promise.
controller.ts
export function getQuestions(req: Request, res: Response) {
const p1 = axios.post('http://localhost:9002/getQuestions', req.body).then(
function(res1) {
return res1.data.Details;
});
const p2 = axios.post('http://localhost:9002/getNoQuestions', req.body).then(
function(res2) {
return res2.data;
});
Promise.all([p1, p2])
.then(function(fullResults) {
const modifiedResults = fullResults;
res.json(modifiedResults);
})
.catch(function(e) {
console.log(e)
});
}
Upvotes: 0
Views: 45
Reputation: 39192
Add catch
clauses to the individual promises instead of relying upon Promise.all error handling
const a = axios.post(...).then(r => r.data.details).catch(e => {
console.log("error from a: ", e);
});
const b = axios.post(...).then(r -> r.data.details).catch(e => {
console.log("error from b: ", e);
});
Promise.all([a, b]).then(([aResult, bResult]) => {
if (aResult && bResult) {
// do something with results
}
});
Upvotes: 1