首页 > 解决方案 > 如何使用承诺检查错误?

问题描述

我有来自客户端的请求,基于传递的参数,我必须进行两次 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)
        });
}

标签: javascriptnode.jspromiseaxios

解决方案


向各个 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
   }
});

推荐阅读