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)
类似,它们不同的是:
promise
的最终状态,所以finally
的回调函数中不接收任何参数,它仅用于无论最终结果如何都要执行的情况。Promise.resolve(2).then(() => {}, () => {})
(resolved的结果为undefined
)不同,Promise.resolve(2).finally(() => {})
resolved的结果为 2
。Promise.reject(3).then(() => {}, () => {})
(resolved 的结果为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; });
规范 | 状态 | 备注 |
---|---|---|
TC39 proposal | Stage 4 |
To contribute to this compatibility data, please write a pull request against this repository: https://github.com/mdn/browser-compat-data.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
finally | Chrome Full support 63 | Edge Full support 18 | Firefox Full support 58 | IE No support No | Opera Full support 50 | Safari Full support 11.1 | WebView Android Full support 63 | Chrome Android Full support 63 | Edge Mobile No support No | Firefox Android Full support 58 | Opera Android Full support 50 | Safari iOS Full support 11.1 | Samsung Internet Android No support No | nodejs Full support 10.0.0 |