--- title: Promise.prototype.finally() slug: Web/JavaScript/Reference/Global_Objects/Promise/finally tags: - JavaScript - Promises - Reference - finally translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally ---
{{JSRef}}
finally() 方法返回一个{{jsxref("Promise")}}。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。这为在Promise是否成功完成后都需要执行的代码提供了一种方式。
这避免了同样的语句需要在{{jsxref("Promise.then", "then()")}}和{{jsxref("Promise.catch", "catch()")}}中各写一次的情况。

语法

p.finally(onFinally);

p.finally(function() {
   // 返回状态为(resolved 或 rejected)
});

参数

onFinally
Promise 结束后调用的{{jsxref("Function")}}。

返回值

返回一个设置了 finally 回调函数的{{jsxref("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; });

规范

Specification Status Comment
{{SpecName('ESDraft', '#sec-promise.prototype.finally', 'Promise.prototype.finally')}} {{Spec2('ESDraft')}}

浏览器兼容性

{{Compat("javascript.builtins.Promise.finally")}}

参见