finally() 方法返回一个Promise,在promise执行结束时,无论结果是fulfilled或者是rejected,在执行then()catch()后,都会执行finally指定的回调函数。这为指定执行完promise后,无论结果是fulfilled还是rejected都需要执行的代码提供了一种方式,避免同样的语句需要在then()catch()中各写一次的情况。

语法

p.finally(onFinally);

p.finally(function() {
   // 返回状态为(resolved 或 rejected)
});参数
onFinally
Promise 状态改变后执行的回调函数。

返回值

返回一个设置了 finally 回调函数的Promise对象。 

描述

如果你想在 promise 执行完毕后无论其结果怎样都做一些处理或清理时,finally() 方法可能是有用的。

finally() 虽然与 .then(onFinally, onFinally) 类似,它们不同的是:

注意: 在finally回调中 throw(或返回被拒绝的promise)将以 throw() 指定的原因拒绝新的promise.

示例

let isLoading = true;

fetch(myRequest).then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Oops, we haven't got JSON!");
  })
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.log(error); })
  .finally(function() { isLoading = false; });

规范

规范 状态 备注
TC39 proposal Stage 4  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
finallyChrome Full support 63Edge Full support 18Firefox Full support 58IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support 63Edge Mobile No support NoFirefox Android Full support 58Opera Android Full support 50Safari iOS Full support 11.1Samsung Internet Android No support Nonodejs Full support 10.0.0

Legend

Full support  
Full support
No support  
No support

参见