Promise reject() 导致“Uncaught (in promise)";警告 [英] Promise reject() causes "Uncaught (in promise)" warning

查看:46
本文介绍了Promise reject() 导致“Uncaught (in promise)";警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用承诺 reject() 回调后,Chrome 控制台中会出现警告消息 Uncaught (in promise)".我想不通背后的原因,也不知道如何摆脱它.

Once a promise reject() callback is called, a warning message "Uncaught (in promise)" appears in the Chrome console. I can't wrap my head around the reason behind it, nor how to get rid of it.

var p = new Promise((resolve, reject) => {
  setTimeout(() => {
    var isItFulfilled = false
    isItFulfilled ? resolve('!Resolved') : reject('!Rejected')
  }, 1000)  
})

p.then(result => console.log(result))
p.catch(error => console.log(error))

警告:

我发现如果 onRejected 处理程序没有显式提供给 .then(onResolved, onRejected) 方法,JS 会自动提供一个隐式的.它看起来像这样: (err) =>抛出错误.自动生成的处理程序将依次抛出.

I found out that if the onRejected handler is not explicitly provided to the .then(onResolved, onRejected) method, JS will automatically provide an implicit one. It looks like this: (err) => throw err. The auto generated handler will throw in its turn.

参考:

如果 IsCallable(onRejected)` 为 false,则
   让 onRejected 成为Thrower".

If IsCallable(onRejected)` is false, then
     Let onRejected be "Thrower".

http://www.ecma-international.org/ecma-262/6.0/index.html#sec-performpromisethen

推荐答案

发生这种情况是因为您没有将 catch 处理程序附加到第一个 then 方法返回的承诺,因此没有处理程序当承诺拒绝时.你确实在最后一行有一个用于承诺 p 的,但没有用于 chained 承诺,由 then 方法,在它之前的行中.

This happens because you do not attach a catch handler to the promise returned by the first then method, which therefore is without handler for when the promise rejects. You do have one for the promise p in the last line, but not for the chained promise, returned by the then method, in the line before it.

正如您在下面的评论中正确添加的那样,当未提供捕获处理程序(或它不是函数)时,默认会抛出错误.在承诺链中,这个错误可以用 catch 方法回调捕获,但如果没有,JavaScript 引擎将像处理任何其他未捕获的错误一样处理该错误,并应用默认值处理程序,这会导致您在控制台中看到的输出.

As you correctly added in comments below, when a catch handler is not provided (or it's not a function), the default one will throw the error. Within a promise chain this error can be caught down the line with a catch method callback, but if none is there, the JavaScript engine will deal with the error like with any other uncaught error, and apply the default handler in such circumstances, which results in the output you see in the console.

为了避免这种情况,将 .catch 方法链接到第一个 then 返回的 promise,如下所示:

To avoid this, chain the .catch method to the promise returned by the first then, like this:

p.then( result =>  console.log('Fulfilled'))
 .catch( error =>  console.log(error) );

这篇关于Promise reject() 导致“Uncaught (in promise)";警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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