【问题标题】:How to handle the Error using the Promises如何使用 Promises 处理错误
【发布时间】:2017-01-08 15:07:21
【问题描述】:

这是我的代码,我刚开始学习 Promises,尝试使用 Promise Catch 块处理错误,有没有办法只使用一个 catch 块来处理这两个错误,在我的代码中,我使用两个 catch 块来处理错误。任何 bdy 都可以帮我解决这个问题。

 exports.create = function (req, res) {
        DetailsValidator.validator.keyValidator(req.body).then(success=>{
            return true
        }).then((result)=>{
            console.log("coming Body is", req.body);
            let acount = new CloudAccountDetailSchema();
            acount.type = 1;// For Aws its type is one
            acount.owner = 212;
            acount.projectId = req.query.pId;
            acount.save().then(accountDetail=> {
                res.status(201).json({
                    success: true,
                    data: {
                        message: " account successfully added"
                    }
                })
            }).catch((e)=>{
                return res.status(409).send({
                    success: false,
                    message: e
                });
            })
        }).catch(err => {
            return res.status(409).send({
                success: false,
                message: err
            });
        })

    };

【问题讨论】:

标签: javascript node.js promise es6-promise


【解决方案1】:

您可以扁平化您的 Promise 链并将所有内容传播到最终的 catch 块。请记住,您可以在 .then(...) 回调中返回一个 Promise,并将您的 Promise 状态转换为该新 Promise 的状态:

exports.create = function (req, res) {
  DetailsValidator.validator.keyValidator(req.body).then(success=>{
    return true
  }).then((result)=>{
    console.log("coming Body is", req.body);
    let acount = new CloudAccountDetailSchema();
    acount.type = 1;// For Aws its type is one
    acount.owner = 212;
    acount.projectId = req.query.pId;
    return acount.save();
  }).then(accountDetail=> {
    res.status(201).json({
      success: true,
      data: {
        message: " account successfully added"
      }
    });
  }).catch(err => {
    return res.status(409).send({
      success: false,
      message: err
    });
  });
}

【讨论】:

    【解决方案2】:

    您可以使用已实现 catch 的 BlueBird 或 Q 等库,但您可以使用 async/await 轻松完成,如下所示:

    async function someFunction(){
      try{ 
       const firstPromise = await someAsyncFunction()
       const secondPromise = await $.ajax({ ... })
       console.log(firstPromise)
       return secondPromise
      }catch(e){
        console.log('Catch any error in the block only once')
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-11
      • 2019-01-15
      • 2016-11-05
      • 2018-10-26
      • 2014-07-03
      • 2018-12-21
      • 2013-03-10
      • 2018-06-20
      • 2014-05-27
      相关资源
      最近更新 更多