Raz*_*Raz 3 javascript node.js
UnhandledPromiseRejectionWarning 在异步等待中
我有以下代码:
function foo() {
return new Promise((resolve, reject) => {
db.foo.findOne({}, (err, docs) => {
if (err || !docs) return reject();
return resolve();
});
});
}
async function foobar() {
await foo() ? console.log("Have foo") : console.log("Not have foo");
}
foobar();
Run Code Online (Sandbox Code Playgroud)
结果如下:
(节点:14843)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):false
(节点:14843)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零的退出代码终止Node.js进程。
注意:我知道我可以解决以下问题:
foo().then(() => {}).catch(() => {});
Run Code Online (Sandbox Code Playgroud)
但是,然后我们“回到”回调异步样式。
我们如何解决这个问题?
将代码包装成try-catch块。
async function foobar() {
try {
await foo() ? console.log("Have foo") : console.log("Not have foo");
}
catch(e) {
console.log('Catch an error: ', e)
}
}
Run Code Online (Sandbox Code Playgroud)
then(() => {}).catch(() => {})不需要,因为catch不一定应该追求then。
UnhandledPromiseRejectionWarning表示一个诺言未与同步链接catch,从而导致未处理的拒绝。
在中async..await,错误应被捕获try..catch:
async function foobar() {
try {
await foo() ? console.log("Have foo") : console.log("Not have foo");
} catch (error) {
console.error(error);
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是在顶层处理错误。如果foobar是应用程序入口点,并且不应该链接到其他任何地方,则为:
foobar().catch(console.error);
Run Code Online (Sandbox Code Playgroud)
问题foo在于它不提供有意义的错误。最好应该是:
if (err || !docs) return reject(err);
Run Code Online (Sandbox Code Playgroud)
同样,大多数流行的基于回调的库都承诺会避免使用new Promise。它mongoist为mongojs。
| 归档时间: |
|
| 查看次数: |
4519 次 |
| 最近记录: |