--- 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 ---
finally() 方法返回一个{{jsxref("Promise")}}。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。这为在Promise是否成功完成后都需要执行的代码提供了一种方式。p.finally(onFinally);
p.finally(function() {
// 返回状态为(resolved 或 rejected)
});
onFinallyPromise 结束后调用的{{jsxref("Function")}}。返回一个设置了 finally 回调函数的{{jsxref("Promise")}}对象。
如果你想在 promise 执行完毕后无论其结果怎样都做一些处理或清理时,finally() 方法可能是有用的。
finally() 虽然与 .then(onFinally, onFinally) 类似,它们不同的是:
promise的最终状态,所以finally的回调函数中不接收任何参数,它仅用于无论最终结果如何都要执行的情况。Promise.resolve(2).then(() => {}, () => {}) (resolved的结果为undefined)不同,Promise.resolve(2).finally(() => {}) resolved的结果为 2。Promise.reject(3).then(() => {}, () => {}) (fulfilled的结果为undefined), Promise.reject(3).finally(() => {}) rejected 的结果为 3。备注: 在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")}}