The origin of this error lies in the fact that each and every promise is expected to handle promise rejection ie have a .catch(...) .(这个错误的根源在于每个承诺都应该处理承诺拒绝,即具有.catch(...) 。)
you can avoid the same by adding .catch(...) to a promise in the code as given below.(您可以通过在代码中的promise中添加.catch(...)来避免相同的操作,如下所示。)
for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar(例如,函数PTest()将根据全局变量somevar的值来解析或拒绝promise)
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");
});
In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises.(在某些情况下,即使我们为promises编写了.catch(..),也会出现“未处理的promise promise”消息。) It's all about how you write your code.(这都是关于你如何编写代码的。) The following code will generate "unhandled promise rejection" even though we are handling catch
.(即使我们正在处理catch
,下面的代码也会生成“未处理的promise promise” 。)
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");
});
The difference is that you don't handle .catch(...)
as chain but as separate.(区别在于您不将.catch(...)
作为链处理,而是作为单独处理。) For some reason JavaScript engine treats it as promise without un-handled promise rejection.(出于某种原因,JavaScript引擎将其视为承诺而没有未处理的承诺拒绝。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…