当嵌套的promise块中发生错误时,需要在最后一个外部catch块中捕获所有错误。
let docs = {
total: 0,total_downloaded: 0,plan_type: null,};
Document.findAll({
where: {
report_request_id: req.params.requestId
},attributes: ["id","folder_name","total_file"],})
.then(documents => {
documents.forEach(document => {
docs.total += 1;
if (document.get("status") == 1) {
docs.total_downloaded += 1;
}
});
})
.then(function() {
Request.findOne({
where: {
id: req.params.requestId
}
})
.then(request => {
//Suppose I got error here
docs.plan_type = request.plan_type;
})
.catch(err => {
// Block A
throw err;
});
})
.then(function() {
res.status(200).send(docs);
})
.catch(err => {
// Block B
res.status(400).send(err);
});
到目前为止,即使在catch块A中出现错误,我也每次都会获得成功(200)