当嵌套的 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)
最佳答案
您错过了链接 return
promise 的 Request.findOne()
语句。
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() {
return 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);
});
关于javascript - 在 Node js 中处理嵌套 promise 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992616/