看上去 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()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
另一个差异与错误处理以及如何解决 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
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
这里的重点是,除非有非常特殊的原因,否则不应该替换 then() 和 finally()。 根据经验,finally() 应该用于清理(清除超时,使引用为空,重置 UI 状态等)。