如何使用Promises处理错误

时间:2017-01-08 06:48:52

标签: javascript node.js promise es6-promise

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

 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
            });
        })

    };

2 个答案:

答案 0 :(得分:2)

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

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
    });
  });
}

答案 1 :(得分:0)

您可以使用像BlueBird或Q这样已经实现了catch的库,但您可以使用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')
  }
}