javascript - 如何使用承诺检查错误?
问题描述
我有来自客户端的请求,基于传递的参数,我必须进行两次 api 调用,所以为了实现这一点,我使用了 promise.all。我想弄清楚我们在第二个承诺中是否有错误,你将如何在第一个承诺中发现错误?
此外,如果在以下情况下有任何更好的方法来处理承诺,请告知我是相当新的承诺。
控制器.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
}
});
推荐阅读
- angular - TS 类中的 Angular 数据绑定
- reactjs - React 如何实现它的双向数据绑定?
- angular - 以角度更改日期选择器的日期格式的问题
- python - 对 rgb 颜色分量执行 sobel 过滤器
- reactjs - 单击后如何获取登录按钮以导航到新页面。我已经下载并使用了 React 路由器 dom
- c# - C#:“函数”没有重载匹配委托 System.Threading.WaitCallBack
- python - Matplotlib 入门
- c# - ASP.NET MVC 实体框架查询搜索
- powershell - 从数组中删除“较小”条目
- node.js - npm install 卡在提取:zone.js