clearTimeout 后出现 UnhandledPromiseRejectionWarning

UnhandledPromiseRejectionWarning after clearTimeout

如果我在拒绝承诺后清除计时器 - 无论我是否拦截承诺 'catch',我都会在标准输出中收到警告 "UnhandledPromiseRejectionWarning"

已检查:节点 v10,节点 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上调用Promise#finally,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 returns 一个将被履行(除非抛出新错误或从 catch 回调中返回被拒绝的 Promise)。