我有来自客户端的请求,基于传递的参数,我必须进行两个 api 调用,所以为了实现这一点,我使用了promise.all。我想弄清楚第二个 promise 是否有错误,您如何捕获第一个 promise 的错误?
此外,如果在以下情况下有更好的方法来处理 promise ,请告知我对 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)
});
}
最佳答案
向各个 Promise 添加 catch
子句,而不是依赖 Promise.all 错误处理
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
}
});
关于javascript - 如何使用 promise 检查错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047472/