From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../global_objects/promise/finally/index.html | 102 +++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html (limited to 'files/zh-tw/web/javascript/reference/global_objects/promise/finally') diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..eef15faf9a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,102 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +
{{JSRef}}
+ +

finally() 方法會回傳一個 {{jsxref("Promise")}}。當 promise 被 settled 後,無論其結果是 fulfilled 還是 rejected ,都會執行指定的回呼函數。它提供了一個讓 Promise 在被確認後,無論是 fulfilled 或是 rejected 都會執行某些程式碼的一種手段。

+ +

這樣可以避免你在 promise 的 {{jsxref("Promise.then", "then()")}} 和 {{jsxref("Promise.catch", "catch()")}} 重複處理相同的程式碼。

+ +

Syntax

+ +
p.finally(onFinally);
+
+p.finally(function() {
+   // settled(fulfilled 或 rejected)
+});
+
+ +

Parameters

+ +
+
onFinally
+
Promise settled 後呼叫的 {{jsxref("Function")}}。
+
+ +

Return value

+ +

回傳 {{jsxref("Promise")}} 當 finally 的處理函數 onFinally 被指定時。

+ +

Description

+ +

當你希望在 promise settled 後且不關心它的結果為何時,執行一些處理或清理的工作, finally() 方法會很有幫助。

+ +

finally() 方法非常類似於 .then(onFinally, onFinally) 的呼叫方式,但仍有一些差異:

+ + + +
+

備註: 在 finally 回呼中使用 throw (或回傳 rejected promise)會導致新的 promise 被 reject , reject 的原因則是呼叫 throw() 時所指定的值。

+
+ +

Examples

+ +
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; });
+
+
+ + + +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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