看上去 promise.prototype.then()
和 promise.prototype.finally
似乎非常相似。但是你需要明白它们有一些重要的差异。
第一个也最明显的是 finally()
没有得到 promise 链的结果。由于 finally()
没有收到值,因此无法更改 promise 的已解决值。
new Promise((resolve, reject) => resolve(10))
.then(x => {
console.log(x); // 10
return x + 1;
})
.finally(x => {
console.log(x); // undefined
return x + 2;
});
// Promise resolves to 11, the return value of then()
另一个差异与错误处理以及如何解决 promise 链有关。有时,您可能想要推迟捕获 promise 链中的错误,从而允许你在其他地方处理。在这种情况下,promise 链的 then()
将不会被执行,而 finally()
会。并且如果上一个 catch()
抛出,你最终会处于相同的情形之下。
new Promise((resolve, reject) => reject(0))
.catch(x => {
console.log(x); // 0
throw x;
})
.then(x => {
console.log(x); // 将不会执行
})
.finally(() => {
console.log('clean up'); // 'clean up'
});
// Uncaught (in promise) 0
这里的重点是,除非有非常特殊的原因,否则不应该替换 then()
和 finally()
。 根据经验,finally()
应该用于清理(清除超时,使引用为空,重置 UI 状态等)。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有