From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../global_objects/promise/finally/index.html | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/promise/finally/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/promise/finally/index.html') diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/finally/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..6f0711e765 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,101 @@ +--- +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; });
+
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-promise.prototype.finally', 'Promise.prototype.finally')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf