q.promise无法捕获节点js上的拒绝响应

时间:2017-12-25 04:27:19

标签: node.js express

我对我的承诺有一些问题,我承诺检查已删除状态,所以如果状态被删除,承诺将被拒绝,否则将被解决,但q承诺不会捕获拒绝回复,我不知道是什么&# 39;错了,这是我的代码

//Promises

function checkDeleted(status){
   // 'status' return 0 or 1
   var deleted = 1
   var notDeleted = 0

   return Q.promise(function (resolve, reject){
      console.log("check deleted executed")
      if (status == notDeleted){
         console.log('Deleted Status: ' + status)
         resolve(status)
      } else {
         console.log("Else executed") // if i try to update data that has been deleted, it will be executed, actually this already executed after i am try to update data
         reject(new Error("Data has been deleted"))
      }
   })
}

//Handler
function updateTodo(req, res){
   Todo.findById(req.params.id, function (err, response){
      if (!err){
         checkDataValidated(response)
         .then(checkDeleted(response.deleted)) //this should be return reject response
         .then(dataUpdate(response, req))
         .then(saveDataUpdated(response))
         .then(function (data){
            res.json({"data":"all data already updated"})
         })
         .catch(function (error){
            res.send(error)// But reject response not catch here
         })
         .done()
      }
   })
}

1 个答案:

答案 0 :(得分:0)

通过编写代码的方式,所有函数在.findById回调完成后立即运行。你需要将它们变成像() => checkDeleted(response.deleted)这样的闭包。

我还建议您重写此内容以使用async / await,因为它更容易推理:

async function updateTodo(req, res) {
   const response = await Todo.findById(req.params.id);
   try {
     await checkDataValidated(response);
     // This will throw an error if it rejects
     await checkDeleted(response.deleted);
     await dataUpdate(response, req);
     const data = await saveDataUpdated(response);
     res.json({"data":"all data already updated"});
   } catch (error) {
     res.send(error);
   }
}