Promise.prototype.finally() - JavaScript 编辑
The finally()
method returns a Promise
. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise
has been dealt with.
This helps to avoid duplicating code in both the promise's then()
and catch()
handlers.
Syntax
p.finally(onFinally); p.finally(function() { // settled (fulfilled or rejected) });
Parameters
onFinally
- A
Function
called when thePromise
is settled.
Return value
Returns a Promise
whose finally
handler is set to the specified function, onFinally
.
Description
The finally()
method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.
The finally()
method is very similar to calling .then(onFinally, onFinally)
however there are a couple of differences:
- When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it
- A
finally
callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. So for example:- Unlike
Promise.resolve(2).then(() => {}, () => {})
(which will be resolved withundefined
),Promise.resolve(2).finally(() => {})
will be resolved with2
. - Similarly, unlike
Promise.reject(3).then(() => {}, () => {})
(which will be fulfilled withundefined
),Promise.reject(3).finally(() => {})
will be rejected with3
.
- Unlike
Note: A throw
(or returning a rejected promise) in the finally
callback will reject the new promise with the rejection reason specified when calling throw
.
Examples
Using finally
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.error(error); /* this line can also throw, e.g. when console = {} */ })
.finally(function() { isLoading = false; });
Please do not add polyfills on MDN pages. For more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Promise.prototype.finally' in that specification. |
Browser compatibility
BCD tables only load in the browser
To contribute to this compatibility data, please write a pull request against this repository: https://github.com/mdn/browser-compat-data.See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论