虽然满足条件,但以下代码不处理错误。请帮忙理解原因
编辑:下面的代码现在会在满足条件的情况下终止代码流,但会抛出错误导致未处理的拒绝。
utils.js
const isMaximum = Id => {
return db.Entries
.findAndCountAll()
.then(counts => {
let numberOfEntries = 2;
let maxEntries = 2;
if (numberOfEntries == maxEntries) {
return true;
}
else{
return false;
}
});
};
xyz.js
const doSomething=(req,res,next)=>{
Utils.isMaximum(id).then(isLimit=> {
if(isLimit) throw new Error("not allowed"); //unhandled rejection
//rest of code gets terminated as expected
});
}
相关问题Why can I not throw inside a Promise.catch handler?找不到我的解决方案。所以请说清楚。
最佳答案
将其放入 .catch()
处理程序中会使 Promise 链成为被拒绝的 Promise。如果您没有后续的 .catch()
处理程序,那么它将被报告为未处理的 promise 拒绝,因为您之后没有 .catch()
来捕获拒绝的 promise 。这几乎总是一个编程错误,这就是您收到警告的原因。
扔进.catch()
不会终止你的程序。该异常被 Promise 基础设施捕获(并变成被拒绝的 Promise)。这就是 promise 的工作原理(根据规范)。如果您希望程序在此时终止,则可以调用 process.exit() 而不是抛出异常。
现在您已经编辑了您的问题,现在您尝试将其放入 .then()
处理程序中。好的。我将解决您添加的内容。下次请从整个代码上下文开始,以便我们更快地了解情况。
Utils.isMaximum()
是异步的。它返回一个 promise 。您需要使用异步技术进行编程。你不能像同步顺序代码那样思考。调用 Utils.isMaximum()
之后的任何代码都将在调用 .then()
处理程序之前执行。
这是一个简单的例子:
Utils.isMaximum(id).then(isLimit => {
console.log("A");
});
console.log("B");
这将输出:
B
A
因此,对于初学者来说,您无法通过在 .then()
内执行的任何操作来阻止 .then()
block 之后的代码运行阻塞,因为函数的其余部分在 .then()
处理程序执行之前执行。
因此,处理这个问题的通常方法是必须将其余代码放在 .then()
处理程序中或从那里调用的函数中:
const doSomething=(req,res,next)=>{
Utils.isMaximum(id).then(isLimit=> {
if(!isLimit){
// rest of code here that sends regular response
} else {
// handle error here - send error response
// or OK to throw here, throw will be caught by next .catch()
}
}).catch(err => {
// send error response here
});
}
关于javascript - 根据 promise 的结果抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48838789/