promise.prototype.then()和promise.prototype.finally好像很像。但是您需要了解它们有一些重要的区别。第一个也是最明显的是finally()没有得到承诺链的结果。由于finally()没有收到值,因此无法更改承诺的已解决值。newPromise((resolve,reject)=>resolve(10)).then(x=>{console.log(x);//10returnx+1;}).finally(x=>{console.log(x);//undefinedreturnx+2;});//Promiseresolvesto11,thereturnvalueofthen()另一个区别与错误处理和promise链的解析方式有关。有时,您可能希望推迟捕获promise链中的错误,以便在其他地方处理它们。在这种情况下,promise链的then()不会被执行,但finally()会。如果前面的catch()抛出异常,您最终会遇到同样的情况。newPromise((resolve,reject)=>reject(0)).catch(x=>{console.log(x);//0throwx;}).then(x=>{console.log(x);//不会执行}).finally(()=>{console.log('cleanup');//'cleanup'});//Uncaught(inpromise)0这里的重点是,除非有非常具体的原因,否则then()和finally()不应该被替换。根据经验,finally()应该用于清理(清除超时、清空引用、重置UI状态等)。
