簡體   English   中英

如何使用承諾處理錯誤

[英]How to handle the Error using the Promises

這是我的代碼,我剛剛開始學習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
            });
        })

    };

您可以拉平Promise鏈,並使所有內容傳播到最終的catch塊。 請記住,您可以在.then(...)回調中返回一個.then(...) ,並將您的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
    });
  });
}

您可以使用已實現捕獲的諸如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')
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM