从表面上看,Promise.prototype.then()和Promise.prototype.finally()似乎很相似。但是我们需要记住一些重要的区别。
第一个也是最明显的一个是它finally()没有收到承诺链的结果值。同样,由于 finally() 没有收到任何值,因此也无法更改 promise 的已解析值。
JavaScript
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 链中捕获错误,以便在其他地方处理它们。在这种情况下,then()不会执行链接的,而finally()会执行。此外,如果前一个catch()抛出异常,你最终会处于同样的情况。
new Promise((resolve, reject) => reject(0))
.catch(x => {
console.log(x); // 0
throw x;
})
.then(x => {
console.log(x); // Will not run
})
.finally(() => {
console.log('clean up'); // 'clean up'
});
// Uncaught (in promise) 0
这里的要点是你不应该替代then(),finally()除非有非常具体的理由这样做。根据经验,finally()应该用于清理(清除超时、清空引用、重置 UI 状态等)。
更多内容请访问我的网站:https://www.icoderoad.com