javascript - 承诺 then() 和 catch() UnhandledPromiseRejectionWarnin
问题描述
UnhandledPromiseRejectionWarning
当我运行这个简单的代码时,我得到了:
var d = new Promise((resolve, reject) => {
if (false) {
resolve('hello world');
} else {
reject('no bueno');
}
});
d.then((data) => console.log('success : ', data));
d.catch((error) => console.error('error : ', error));
完整的回应是:
error : no bueno
(node:12883) UnhandledPromiseRejectionWarning: no bueno
(node:12883) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:12883) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
好像d.catch()
被解雇了 我注意到如果注释掉d.then()
,警告信息就会消失。
我正在从终端调用脚本,例如node foobar.js
.
难道我做错了什么?
在 MacOS High Sierra 下使用节点 v8.14、v10 和 v11 进行测试。
解决方案
d.then()
创建一个由于被拒绝而被拒绝的新承诺d
。那是没有正确处理的被拒绝的承诺。
您应该链接.then
而.catch
不是:
d
.then((data) => console.log('success : ', data))
.catch((error) => console.error('error : ', error));
推荐阅读
- java - 将 Java 按位“与”运算符转换为 Kotlin
- python - 从文本文件中打印给定字符串的所有字谜
- firebase - react-native-firebase Crashlytics 在 Android 上出现错误
- eclipse - 如何更改日食行号背景颜色?
- android-studio - 无法在 android studio 上运行我的新 Android APP
- java - 在一个数组中,我如何更新值,以便在选择一个项目时,库存下降?
- ios - 更改所有 UIViewControllers 背景
- shopify - 如何确定 Shopify 中 all_products 的所有用途?
- swift - 使用 NSException 关闭时 iOS 应用程序崩溃
- drools - Drools 高内存消耗(版本 7.13.Final)