什么是未处理的承诺拒绝? [英] What is an unhandled promise rejection?

查看:71
本文介绍了什么是未处理的承诺拒绝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要学习Angular 2,我正在尝试他们的教程.

For learning Angular 2, I am trying their tutorial.

我遇到这样的错误:

(node:4796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (r                                                                                                     ejection id: 1): Error: spawn cmd ENOENT
[1] (node:4796) 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.

我在SO中经历了不同的问题和答案,但找不到未处理的承诺拒绝"是什么.

I went through different questions and answers in SO but could not find out what an "Unhandled Promise Rejection" is.

任何人都可以简单地解释一下它是什么,Error: spawn cmd ENOENT是什么,什么时候出现,以及为了消除此警告我需要检查什么?

Can anyone simply explain me what it is and also what Error: spawn cmd ENOENT is, when it arises and what I have to check to get rid of this warning?

推荐答案

此错误的根源在于,每个承诺都应处理承诺拒绝,即具有 .catch(. ..) .您可以通过将 .catch(...) 添加到以下代码中的promise中来避免相同的情况.

The origin of this error lies in the fact that each and every promise is expected to handle promise rejection i.e. have a .catch(...) . you can avoid the same by adding .catch(...) to a promise in the code as given below.

例如,函数PTest()将基于全局变量 somevar

for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar

var somevar = false;
var PTest = function () {
    return new Promise(function (resolve, reject) {
        if (somevar === true)
            resolve();
        else
            reject();
    });
}
var myfunc = PTest();
myfunc.then(function () {
     console.log("Promise Resolved");
}).catch(function () {
     console.log("Promise Rejected");
});

在某些情况下,即使我们为承诺编写了.catch(..),也会出现 未处理的承诺被拒绝" 消息.这一切都与您如何编写代码有关.即使我们正在处理catch,以下代码也会生成 未处理的承诺拒绝" .

In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises. It's all about how you write your code. The following code will generate "unhandled promise rejection" even though we are handling catch.

var somevar = false;
var PTest = function () {
    return new Promise(function (resolve, reject) {
        if (somevar === true)
            resolve();
        else
            reject();
    });
}
var myfunc = PTest();
myfunc.then(function () {
     console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
     console.log("Promise Rejected");
});

区别在于您不将.catch(...)当作链条而是单独处理.出于某种原因,JavaScript引擎将其视为没有未经处理的承诺被拒绝的承诺.

The difference is that you don't handle .catch(...) as chain but as separate. For some reason JavaScript engine treats it as promise without un-handled promise rejection.

这篇关于什么是未处理的承诺拒绝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆