javascript - clearTimeout 后出现 UnhandledPromiseRejectionWarning

标签 javascript node.js es6-promise cleartimeout

<分区>

如果我在拒绝 promise 后清除计时器 - 无论我是否拦截 promise 的“捕获”,我都会在标准输出中收到警告“UnhandledPromiseRejectionWarning”

已检查: Node v10、 Node v12、google-chrome 76

let timer;
const promise = new Promise((resolve, reject) => {
    timer = setTimeout(() => {
        console.log('!timeout');
        reject('timeout error');
    });
}, 100);

promise.then(result => {
    console.log('SUCCESS:', result);
}).catch(error => {
    console.log('!onerror');
    console.error('ERROR:', error);
});

promise.finally(() => {
    console.log('!onfinnaly');
    clearTimeout(timer);
});

console.log('!endcode');

nodejs 中的控制台输出:

!endcode
!timeout
!onfinnaly
!onerror
ERROR: timeout error
(node:12697) UnhandledPromiseRejectionWarning: timeout error
(node:12697) 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:12697) [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.

google-chrome 中的控制台输出:

!endcode
!timeout
!onfinnaly
!onerror
ERROR: timeout error
Promise.catch (async)
Uncaught (in promise) timeout error

最佳答案

如果您调用 Promise#finally在被拒绝的 Promise 上,finally 返回的 Promise 也被拒绝:

window.addEventListener('unhandledrejection', _ => console.error( 'Unhandled Rejection' ) );

Promise.reject( )
  .finally( _ => _ );

如果你可能最终调用一个被拒绝的 Promise,你仍然需要捕获错误以防止未处理的拒绝:

window.addEventListener('unhandledrejection', _ => console.error( 'Unhandled Rejection' ) );

Promise.reject( 'foobar' )
  .finally( _ => _ )
  .catch( e => console.log( 'Caught: ' + e ) );

如果你在 catch 之后链接你的 finally,而不是直接在你的 promise 上调用它,你不会有未处理的拒绝,因为 catch 返回一个 Promise,它将被履行(除非抛出新错误或从 catch 回调中返回被拒绝的 Promise)。

关于javascript - clearTimeout 后出现 UnhandledPromiseRejectionWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503001/

相关文章:

node.js 从原始 http 请求字符串创建对象

javascript - 在类中实现链式 es6 Promise

javascript - 重定向时通过其他页面上的 url 调用 javascript 函数

javascript - jquery tablesorter滚动条: how set focus to scroll by keydown

javascript - 使用 Snap.svg 选择 Fragment 的 <svg> 根

javascript - 压缩多个 promise

reactjs - 我如何将嵌套的 promise 传递给异步等待

javascript - 是否有可能在任何地方使用自动化执行 Javascript 函数?

node.js - Hapi js - makemehapi 问题

node.js - 如何知道 Node js 是否安装了特定的 Windows 服务?