diff --git a/files/zh-tw/learn/javascript/asynchronous/index.md b/files/zh-tw/learn/javascript/asynchronous/index.md index 75abee1697c512..c754e606d55393 100644 --- a/files/zh-tw/learn/javascript/asynchronous/index.md +++ b/files/zh-tw/learn/javascript/asynchronous/index.md @@ -17,50 +17,41 @@ tags: - setTimeout - 非同步的 --- -
在本單元我們來討論非同步的( {{Glossary("asynchronous")}} ) {{Glossary("JavaScript")}} ,為何其如此重要,並了解它如何有效率的處理像是從伺服器獲取資源的這類潛在性阻塞( blocking )操作
+在本單元我們來討論非同步的( {{Glossary("asynchronous")}} ) {{Glossary("JavaScript")}} ,為何其如此重要,並了解它如何有效率的處理像是從伺服器獲取資源的這類潛在性阻塞( blocking )操作 -我們已為你準備一門實現你目標所需要具備的所有基礎知識課程
+## 事前準備 - +非同步的 JavaScript 是一個相當進階的主題,因此建議你在嘗試本單元前能先通過 [JavaScript 初探](/zh-TW/docs/Learn/JavaScript/First_steps)以及 [JavaScript 構成元素](/zh-TW/docs/Learn/JavaScript/Building_blocks)單元。 -非同步的 JavaScript 是一個相當進階的主題,因此建議你在嘗試本單元前能先通過 JavaScript 初探以及 JavaScript 構成元素單元。
+## 指南 -如果你對非同步程式設計的概念還不太熟悉,強烈建議你應該先從非同步程式設計通用概念的文章開始學習。如果你已經具備其概念,那麼你或許可以跳至非同步的 JavaScript 介紹單元開始。
+- [非同步程式設計通用概念](/zh-TW/docs/Learn/JavaScript/Asynchronous/Concepts) + - : 在本篇文章我們會介紹一些關於非同步程式設計的重要觀念,以及在網頁瀏覽器和 JavaScript 中的行為。在閱讀其他文章之前你應該先具備這些觀念。 +- [非同步的 JavaScript 介紹](/zh-TW/docs/Learn/JavaScript/Asynchronous/Introducing) + - : 在本篇文章中我們會先簡短的回顧我們在同步的 JavaScript 中所遭遇到的問題,並預先看看稍後將會使用哪些非同步的 JavaScript 技巧來解決此問題。 +- [協同的非同步 JavaScript : Timeout 和 interval](/zh-TW/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals) + - : 在這裡看看我們在傳統上是如何透過設定的時間到期或是透過定時的方式(例如:每秒發生的次數)讓 Javascript 能夠以非同步的方式執行程式碼,談談這些方法有哪些用處以及存在哪些既有的問題。 +- [優雅的使用 Promise 來處理非同步操作](/zh-TW/docs/Learn/JavaScript/Asynchronous/Promises) + - : Promise 是在 Javascript 語言中相對較新的功能,它能夠讓你延遲活動直到先前的活動回報完成或失敗。這方法對設置一連串的操作並讓其正確的循序執行相當有用。本篇文章向你展示 Promise 是如何運作,你將會看到如何被使用在 WebAPI ,以及如何寫出屬於自己的 Promise 。 +- [利用 async 及 await 讓非同步程式設計變得更容易](/zh-TW/docs/Learn/JavaScript/Asynchronous/Async_await) + - : Promise 在設置上可能會有些複雜並難以理解,因此現代瀏覽器已經實作出 `async` 函式以及 `await` 運算子。前者能夠讓標準的函式隱含的使用 Promise 方式來實現非同步行為,然而後者可以被用在 `async` 函式內部,讓程式碼繼續執行之前去等待一個 Promise 完成。這能讓我們在鏈結一連串的 Promise 的情況之下更加簡潔易懂。 +- [選擇正確的方法](/zh-TW/docs/Learn/JavaScript/Asynchronous/Choosing_the_right_approach) + - : 在結束本單元前,我們將會從先前所討論過的不同程式技巧和功能,幫助你考量在甚麼情況下應該使用哪一個,並適當的提供一些有關常見的陷阱的建議及提醒。 - +## 參閱 -在本篇文章我們會介紹一些關於非同步程式設計的重要觀念,以及在網頁瀏覽器和 JavaScript 中的行為。在閱讀其他文章之前你應該先具備這些觀念。
-async
函式以及 await
運算子。前者能夠讓標準的函式隱含的使用 Promise 方式來實現非同步行為,然而後者可以被用在 async
函式內部,讓程式碼繼續執行之前去等待一個 Promise 完成。這能讓我們在鏈結一連串的 Promise 的情況之下更加簡潔易懂。在本篇文章中我們會先簡短回顧在同步的 JavaScript 中所遭遇到的問題,並預先看看往後將會使用哪些非同步的 JavaScript 技巧來解決此問題。
+在本篇文章中我們會先簡短回顧在同步的 JavaScript 中所遭遇到的問題,並預先看看往後將會使用哪些非同步的 JavaScript 技巧來解決此問題。先備知識: | -基本的電腦概念,理解 JavaScript 的基本原理。 | -
---|---|
學習目標: | -熟悉什麼是非同步的 Javascript ,與同步的 Javascript 有甚麼差異,以及有哪些使用案例。 | -
先備知識: | +基本的電腦概念,理解 JavaScript 的基本原理。 | +
學習目標: | ++ 熟悉什麼是非同步的 Javascript ,與同步的 Javascript + 有甚麼差異,以及有哪些使用案例。 + | +
在我們了解什麼是非同步({{Glossary("asynchronous")}} ) JavaScript 之前,我們應該確保我們已經了解什麼是同步( {{Glossary("synchronous")}} ) JavaScript 。在本章節會回顧我們在前篇文章所看到的一些資訊。
+在我們了解什麼是非同步(**{{Glossary("asynchronous")}}** ) JavaScript 之前,我們應該確保我們已經了解什麼是同步( **{{Glossary("synchronous")}}** ) JavaScript 。在本章節會回顧我們在前篇文章所看到的一些資訊。 -我們在前一個學習單元所看到的大部分功能都是同步的——當跑一段程式碼,瀏覽器會將執行結果盡快的回傳。我們來看看一則簡單的範例(線上範例,原始碼):
+我們在前一個學習單元所看到的大部分功能都是同步的——當跑一段程式碼,瀏覽器會將執行結果盡快的回傳。我們來看看一則簡單的範例([線上範例](https://mdn.github.io/learning-area/javascript/asynchronous/introducing/basic-function.html),[原始碼](https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/introducing/basic-function.html)): -const btn = document.querySelector('button'); -btn.addEventListener('click', () => { +```js +const btn = document.querySelector('button'); +btn.addEventListener('click', () => { alert('你點擊了我!'); let pElem = document.createElement('p'); pElem.textContent = '這是一段新加的文字。'; document.body.appendChild(pElem); }); -+``` + +在這個程式區塊,指令是一行接著一行的執行: -
在這個程式區塊,指令是一行接著一行的執行:
+1. 我們先取得已經在 DOM 裡面的 {{htmlelement("button")}} 元素的參考。 +2. 我們加入一個 [`click`](/zh-TW/docs/Web/API/Element/click_event) 事件監聽器,因此當按鈕被點擊時: -click
事件監聽器,因此當按鈕被點擊時:
- alert()
訊息。當正在執行每一個操作時,什麼事情都不會發生——渲染暫時停止。我們在上一篇文章有提到,這是因為 Javascript 是跑在一條單執行緒。主執行緒在同一時間只能做一件事情,直到目前操作完成為止其他的操作都會暫停。
+當正在執行每一個操作時,什麼事情都不會發生——渲染暫時停止。我們在[上一篇文章](/zh-TW/docs/Learn/JavaScript/Asynchronous/Introducing)有提到,這是因為 [Javascript 是跑在一條單執行緒](/zh-TW/docs/Learn/JavaScript/Asynchronous/Concepts#javascript_is_single_threaded)。主執行緒在同一時間只能做一件事情,直到目前操作完成為止其他的操作都會暫停。 -所以在上面的範例中,直到警告視窗的確認按鈕被按下為止之前,文字段落都不會出現。你可以試試看底下的範例:
+所以在上面的範例中,直到警告視窗的確認按鈕被按下為止之前,文字段落都不會出現。你可以試試看底下的範例: - +```html hidden + +``` -{{EmbedLiveSample('同步的 JavaScript', '100%', '70px')}}
+{{EmbedLiveSample('同步的 JavaScript', '100%', '70px')}} -備註: 使用 alert()
有個很重要的事情要記得,雖然用在證明是否為同步的阻塞操作非常有用,但非常不建議用在實際的應用程式上,使用體驗將會相當糟糕。
如同先前所描述的原因(例如:和阻塞有關),現在許多 Web API 功能都是使用非同步程式碼的做法,特別是那些要從外部裝置存取或抓取某些種類資源的功能,像是從網路抓取檔案、存取資料庫並回傳資料、從網路攝影機取得視訊串流或者是將畫面透過廣播的方式顯示到 VR 頭盔等。
+如同先前所描述的原因(例如:和阻塞有關),現在許多 Web API 功能都是使用非同步程式碼的做法,特別是那些要從外部裝置存取或抓取某些種類資源的功能,像是從網路抓取檔案、存取資料庫並回傳資料、從網路攝影機取得視訊串流或者是將畫面透過廣播的方式顯示到 VR 頭盔等。 -為什麼同步的程式碼很難做到這些事?我們快速地看個例子。當你想要從伺服器抓取一張影像,你是沒有辦法馬上獲得結果的。這個意思是下面的程式碼(虛擬碼)是行不通的:
+為什麼同步的程式碼很難做到這些事?我們快速地看個例子。當你想要從伺服器抓取一張影像,你是沒有辦法馬上獲得結果的。這個意思是下面的程式碼(虛擬碼)是行不通的: -let response = fetch('myImage.png'); // fetch is asynchronous +```js +let response = fetch('myImage.png'); // fetch is asynchronous let blob = response.blob(); -// display your image blob in the UI somehow+// display your image blob in the UI somehow +``` -
那是因為你不知道下載影像需要花上多少時間,所以當執行第二行時它將拋出一段錯誤(也許間歇性的發生,也許每一次都發生)這是因為 response
尚未取得結果還不能使用。因此在它嘗試做接下來的任何事之前,你需要讓你的程式碼先等到 response
回傳結果。
你將會在 Javascript 程式碼碰到兩種主要類型的非同步程式碼風格,舊式的回呼風格(callback)以及新式的 promise 風格。在接下來的章節我們將會依次的檢視它們。
+你將會在 Javascript 程式碼碰到兩種主要類型的非同步程式碼風格,舊式的回呼風格(callback)以及新式的 promise 風格。在接下來的章節我們將會依次的檢視它們。 -呼叫一個將在背景開始執行程式碼的函式,非同步回呼是作為該呼叫函式的引數( argument )的函式。當在背景環境執行的程式碼完成時,就會呼叫回呼函式( callback function )讓你知道工作已經結束或者是一些有趣的事情已經發生了。現在回呼似乎有點過時了,但你依然會在一些較舊但仍常被使用的 API 發現到這樣的寫法。
+呼叫一個將在背景開始執行程式碼的函式,非同步回呼是作為該呼叫函式的引數( argument )的函式。當在背景環境執行的程式碼完成時,就會呼叫回呼函式( callback function )讓你知道工作已經結束或者是一些有趣的事情已經發生了。現在回呼似乎有點過時了,但你依然會在一些較舊但仍常被使用的 API 發現到這樣的寫法。 -一個非同步回呼的例子就是作為在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 的第二個參數(正如我們在之前的例子看到的):
+一個非同步回呼的例子就是作為在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 的第二個參數(正如我們在之前的例子看到的): -btn.addEventListener('click', () => { +```js +btn.addEventListener('click', () => { alert('你點擊了我!'); let pElem = document.createElement('p'); pElem.textContent = '這是一段新加的文字。'; document.body.appendChild(pElem); -});+}); +``` -
第一個參數是要被監聽的事件類型,第二個參數是當事件被觸發時會呼叫的回呼函式。
+第一個參數是要被監聽的事件類型,第二個參數是當事件被觸發時會呼叫的回呼函式。 -當我們將回呼函式做為一個引數給其他函式時,我們只傳送該回呼函式的參考做為引數,換句話說,回呼函式並非立即被執行。它將會在呼叫函式的內部某個地方非同步的「回去呼叫」它(因此稱回呼)。呼叫函式有責任的在適當的時機去執行該回呼函式。
+當我們將回呼函式做為一個引數給其他函式時,我們只傳送該回呼函式的參考做為引數,換句話說,回呼函式**並非**立即被執行。它將會在呼叫函式的內部某個地方非同步的「回去呼叫」它(因此稱回呼)。呼叫函式有責任的在適當的時機去執行該回呼函式。 -自己寫一個包含回呼的呼叫函式很容易。我們來看看另一個從 XMLHttpRequest
API 載入資源的例子(線上範例,原始碼):
function loadAsset(url, type, callback) { +```js +function loadAsset(url, type, callback) { let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = type; @@ -129,157 +132,154 @@ function displayImage(blob) { document.body.appendChild(image); } -loadAsset('coffee.jpg', 'blob', displayImage);+loadAsset('coffee.jpg', 'blob', displayImage); +``` -
在這裡我們新增一個 displayImage()
函式,將 blob 做為一個參數傳進去函式來產生物件網址,然後建立一個可以用網址來顯示的影像,並將這個網址附加在 document 的 <body>
標籤內。然而,我們再新增一個 loadAsset()
函式,將回呼作為參數並伴隨抓取資源的網址以及內容型式傳進去函式。它使用 XMLHttpRequest
(通常縮寫成「 XHR 」)根據網址去抓取資源,並將回傳結果傳送到回呼去做一些事情。在這個例子回呼正在等待 XHR 完成下載資源(使用 onload
事件處理器)後,再將資源傳遞給回呼。
回呼是多樣性的——它不只可以讓你控制執行函式的呼叫順序以及在不同函式間傳遞的參數,還可以讓你根據情況將資料傳遞到不同的函式。所以你可以根據下載的回傳結果採取不同的處理方式,例如 processJSON()
, displayText()
等等。
注意不是所有的回呼都是非同步的——有些是跑在同步上。有個例子是當我們使用 {{jsxref("Array.prototype.forEach()")}} 在陣列裡面用迴圈來遍歷每一個項目(線上範例,原始碼):
+注意不是所有的回呼都是非同步的——有些是跑在同步上。有個例子是當我們使用 {{jsxref("Array.prototype.forEach()")}} 在陣列裡面用迴圈來遍歷每一個項目([線上範例](https://mdn.github.io/learning-area/javascript/asynchronous/introducing/foreach.html),[原始碼](https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/introducing/foreach.html)): -const gods = ['Apollo', 'Artemis', 'Ares', 'Zeus']; +```js +const gods = ['Apollo', 'Artemis', 'Ares', 'Zeus']; gods.forEach(function (eachName, index){ console.log(index + '. ' + eachName); -});+}); +``` -
在這個例子我們用迴圈遍歷一個含有希臘諸神名稱的陣列並在控制台印出每一個索引和值。 forEach()
的預期參數是一個回呼函式,它有兩個參數代表陣列每個項目的名稱和索引。然而,它並未等待任何事情——它是立即的執行。
Promise 是作為非同步程式碼的一種新風格樣式,你將會在現代 Web API 看到這種用法。一個好例子是 fetch()
API ,它基本上就像更新穎、更有效率版本的 {{domxref("XMLHttpRequest")}} 。我們藉由從伺服器提取資料這一篇文章快速地來看一個例子吧:
fetch('products.json').then(function(response) { +```js +fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { let products = json; initialize(products); }).catch(function(err) { console.log('Fetch problem: ' + err.message); -});+}); +``` - +> **備註:** 你可以在 GitHub ([原始碼](https://github.com/mdn/learning-area/blob/master/javascript/apis/fetching-data/can-store/can-script.js),[線上範例](https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/))找到最終版本。 -
在這裡我們看到 fetch
()
帶一個參數——你想要在網路上提取資源的網址——並回傳一個 promise 。這一個 promise 用來表示一個完成或失敗的非同步操作的物件。它代表的是一種中間的狀態。本質上,它代表瀏覽器述說著:「我承諾我會盡快給予你一個答覆」,因此名稱就叫做「 promise 」。
我們可以透過練習來習慣這個概念;在動作上它感覺有點像是 薛丁格的貓。任何可能的結果已經發生,所以 fetch 指令正在等待瀏覽器在未來的某個時間點完成操作後並回傳的結果。我們接著在 fetch()
的結束會鏈結三個程式區塊:
then()
區塊。兩個都含有回呼函式且先前的操作成功時就會執行,每一個回呼函式都會收到上一個成功完成操作的結果,因此你可以繼續執行一些事情。每一個 .then()
區塊都會回傳另一個 promise ,代表你可以將多個 .then()
區塊彼此作連結,所以多個非同步操作可以一個接著一個被用來依序執行。.then()
區塊失敗就會跑到 catch()
區塊——類似像在同步區塊內部的 try...catch
做法,在 catch()
內部會提供一個失敗的物件,可以用來報告是發生甚麼類型的錯誤。要注意到同步的 try...catch
不能與 promises 一起做使用,儘管它可以和 async / await 待配使用,這稍後將會學習到。備註: 你將會在稍後的單元學習到更多關於 promise 的觀念,即使現在尚未完全理解你也不需要太擔心。
-像 promise 的非同步的操作被放進事件佇列中,佇列內的任務會在主執行緒完成它自己的工作後執行,所以它並不會阻擋後續 Javascript 程式碼的執行。在佇列內的操作會盡快完成並將結果回傳給 Javascript 環境。
+像 promise 的非同步的操作被放進**事件佇列**中,佇列內的任務會在主執行緒完成它自己的工作後執行,所以它**並不會阻擋**後續 Javascript 程式碼的執行。在佇列內的操作會盡快完成並將結果回傳給 Javascript 環境。 -Promise 和舊式的回呼有一些相似點。他們本質上都是回傳一個物件到回呼函式,而並非必須將回呼傳遞到呼叫函式。
+Promise 和舊式的回呼有一些相似點。他們本質上都是回傳一個物件到回呼函式,而並非必須將回呼傳遞到呼叫函式。 -然而 promise 更是專門設計用來處理非同步的操作,比起舊式的回呼有更多的優點:
+然而 promise 更是專門設計用來處理非同步的操作,比起舊式的回呼有更多的優點: -.then()
來鏈結多的非同步操作,將一個操作的結果作為下一個操作的輸入。這個對經常會導致「死亡金字塔」( pyramid of doom ,通常也被稱作為 回呼地獄)的回呼來說相當難辦到。.catch()
區塊來統一處理,而不是在個別的區塊做處理。我們來探索一個可以更進一步說明非同步程式碼天性的範例,並說明當我們無法充分了解程式碼的執行順序以及嘗試將非同步程式碼當作同步程式碼會發生什麼事。底下的範例和我們之前看到的相當相似( 線上範例,原始碼)。區別在於我們加入一些 {{domxref("console.log()")}} 來說明程式碼是否會依照你以為的順序來執行。
+我們來探索一個可以更進一步說明非同步程式碼天性的範例,並說明當我們無法充分了解程式碼的執行順序以及嘗試將非同步程式碼當作同步程式碼會發生什麼事。底下的範例和我們之前看到的相當相似( [線上範例](https://mdn.github.io/learning-area/javascript/asynchronous/introducing/async-sync.html),[原始碼](https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/introducing/async-sync.html))。區別在於我們加入一些 {{domxref("console.log()")}} 來說明程式碼是否會依照你以為的順序來執行。 -console.log ('Starting'); +```js +console.log ('Starting'); let image; -fetch('coffee.jpg').then((response) => { +fetch('coffee.jpg').then((response) => { console.log('It worked :)') return response.blob(); -}).then((myBlob) => { +}).then((myBlob) => { let objectURL = URL.createObjectURL(myBlob); image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); -}).catch((error) => { +}).catch((error) => { console.log('There has been a problem with your fetch operation: ' + error.message); }); -console.log ('All done!');+console.log ('All done!'); +``` -
瀏覽器將開始執行程式碼,看到第一行顯示 Starting
的 console.log()
並執行它,接著新增一個 image
變數。
接著它會移動至下一行並開始執行 fetch()
區塊,但是因為執行 fetch()
是非同步的且不會阻塞,所以程式碼會跳過 promise 相關的程式碼後繼續執行,因此到達最後All done!
的 console.log()
並顯示在控制台上。
只有在完成 fetch()
並將回傳結果傳送至 .then()
之後,我們才會看到第二個 console.log()
顯示 It worked :)
的訊息出現。所以訊息的出現順序也許與你所期待的順序不同:
如果上面的例子讓你感到混淆,那麼考慮一下下面更簡單的例子:
+如果上面的例子讓你感到混淆,那麼考慮一下下面更簡單的例子: -console.log("registering click handler"); +```js +console.log("registering click handler"); -button.addEventListener('click', () => { +button.addEventListener('click', () => { console.log("get click"); }); -console.log("all done");+console.log("all done"); +``` -
這是一個非常相似的行為——第一個和第三個 console.log()
的訊息將會立即的顯示,但是第二個正在被阻塞直到有人點擊了滑鼠按鈕。和上一個例子運作的方式類似,除了之前的例子在第二步是因為要等待取得資源之後並顯示在螢幕上才會被阻塞住,而不是等待被點擊。
在這個不直觀的例子中,這樣的設定方式可能會導致問題的發生——你不能在同步的程式碼去依賴一個非同步程式碼的執行結果,你不能保證非同步的函式會在瀏覽器執行下一個同步程式碼之前回傳結果。
+在這個不直觀的例子中,這樣的設定方式可能會導致問題的發生——你不能在同步的程式碼去依賴一個非同步程式碼的執行結果,你不能保證非同步的函式會在瀏覽器執行下一個同步程式碼之前回傳結果。 -為了看這個動作,試著在本地複製我們的程式碼,並將最後的 console.log()
的呼叫改成底下的方式:
console.log ('All done! ' + image.src + 'displayed.');+```js +console.log ('All done! ' + image.src + 'displayed.'); +``` -
你應該會在控制台收到一個錯誤的訊息:
+你應該會在控制台收到一個錯誤的訊息: -TypeError: image is undefined; can't access its "src" property+```plain +TypeError: image is undefined; can't access its "src" property +``` -
這是因為在這個時間點瀏覽器試著去執行最後的 console.log()
時 fetch()
還沒有完成執行,所以 image
變數尚未賦予值因而導致錯誤。
備註: 由於安全性考量,你沒辦法呼叫 fetch()
從你的本地檔案系統抓取資料(或者其他在本地的相關操作)如果要在本地執行上面的範例,你需要在本地架起一個網路伺服器來執行。
為了修復 fetch()
這個有問題的範例讓三個 console.log()
的敘述可以依序被執行你可以讓第三個 console.log()
也非同步的被執行。你可以新增一個新的 .then()
再將其放在裡面,這個新增的 .then()
再串連 promise 區塊的倒數第二個結尾;或者也可以將其放入原本的 .then()
中來解決這個問題。試著現在修復這個問題吧。
備註: 如果你的想法卡住,你可以在這裡找到解答(線上範例)。你也可以在我們稍後的優雅的使用 Promise 來處理非同步操作 這個單元找到更多關於 promise 的資訊。
-Javascript 基本上是一個同步性的、阻塞的,且是跑在單一執行緒的程式語言,也就是在同一時間只能執行一個操作。但是瀏覽器所定義的函式和 API 允許我們註冊一個不該被同步執行的函式,且這個函式應該在某些事件發生時需要非同步的被呼叫(到達指定的時間、使用者透過滑鼠互動,或者取得透過從網路所取到的資料)。這代表你可以讓你的程式碼在同時間做一些事情而不需暫停或阻塞你的主執行緒。
+Javascript 基本上是一個同步性的、阻塞的,且是跑在單一執行緒的程式語言,也就是在同一時間只能執行一個操作。但是瀏覽器所定義的函式和 API 允許我們註冊一個不該被同步執行的函式,且這個函式應該在某些事件發生時需要非同步的被呼叫(到達指定的時間、使用者透過滑鼠互動,或者取得透過從網路所取到的資料)。這代表你可以讓你的程式碼在同時間做一些事情而不需暫停或阻塞你的主執行緒。 -我們要讓程式碼同步地或非同步地執行取決於我們要做甚麼。
+我們要讓程式碼同步地或非同步地執行取決於我們要做甚麼。 -有時候我們希望事情能夠立即的被載入並發生。例如某些使用者定義的樣式,你希望網頁能夠盡快地使用那些樣式。
+有時候我們希望事情能夠立即的被載入並發生。例如某些使用者定義的樣式,你希望網頁能夠盡快地使用那些樣式。 -如果我們正在執行一些需要花一點時間的操作,就好比查詢資料庫並將結果填充到模板上,最好的方式是不要在主執行緒上執行並用非同步的方法來完成。隨著時間的學習,你將會了解到在更多的情況下,選擇使用非同步的技巧會比選擇同步的方式來的更合理。
+如果我們正在執行一些需要花一點時間的操作,就好比查詢資料庫並將結果填充到模板上,最好的方式是不要在主執行緒上執行並用非同步的方法來完成。隨著時間的學習,你將會了解到在更多的情況下,選擇使用非同步的技巧會比選擇同步的方式來的更合理。 -{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}}
+{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}} -Promises 是在 Javascript 語言中相對較新的功能,它能夠讓你延遲活動直到先前的活動回報完成或失敗。這方法對設置一連串的操作並讓其正確的循序執行相當有用。本篇文章向您展示 promises 是如何運作,您將會看到如何被使用在 WebAPIs,以及如何寫出屬於自己的 promises。
+**Promises** 是在 Javascript 語言中相對較新的功能,它能夠讓你延遲活動直到先前的活動回報完成或失敗。這方法對設置一連串的操作並讓其正確的循序執行相當有用。本篇文章向您展示 promises 是如何運作,您將會看到如何被使用在 WebAPIs,以及如何寫出屬於自己的 promises。Prerequisites: | -Basic computer literacy, a reasonable understanding of JavaScript fundamentals. | -
---|---|
Objective: | -To understand promises and how to use them. | -
Prerequisites: | ++ Basic computer literacy, a reasonable understanding of JavaScript + fundamentals. + | +
Objective: | +To understand promises and how to use them. | +
We looked at Promises briefly in the first article of the course, but here we'll look at them in a lot more depth.
+We looked at [Promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) briefly in the first article of the course, but here we'll look at them in a lot more depth. -Essentially, a Promise is an object that represents an intermediate state of an operation — in effect, a promise that a result of some kind will be returned at some point in the future. There is no guarantee of exactly when the operation will complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case.
+Essentially, a Promise is an object that represents an intermediate state of an operation — in effect, a _promise_ that a result of some kind will be returned at some point in the future. There is no guarantee of exactly when the operation will complete and the result will be returned, but there _is_ a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case. -Generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is. And of course, it's nice that it doesn't block the rest of the code execution.
+Generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes _far_ too long!), and more interested in being able to respond to it being returned, whenever that is. And of course, it's nice that it doesn't block the rest of the code execution. -One of the most common engagements you'll have with promises is with web APIs that return a promise. Let's consider a hypothetical video chat application. The application has a window with a list of the user's friends, and clicking on a button next to a user starts a video call to that user.
+One of the most common engagements you'll have with promises is with web APIs that return a promise. Let's consider a hypothetical video chat application. The application has a window with a list of the user's friends, and clicking on a button next to a user starts a video call to that user. -That button's handler calls {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} in order to get access to the user's camera and microphone. Since getUserMedia()
has to ensure that the user has permission to use those devices and ask the user which microphone to use and which camera to use (or whether to be a voice-only call, among other possible options), it can block until not only all of those decisions are made, but also the camera and microphone have been engaged. Also, the user may not respond immediately to these permission requests. This can potentially take a long time.
Since the call to getUserMedia()
is made from the browser's main thread, the entire browser is blocked until getUserMedia()
returns! Obviously, that's not an acceptable option; without promises, everything in the browser becomes unusable until the user decides what to do about the camera and microphone. So instead of waiting for the user, getting the chosen devices enabled, and directly returning the {{domxref("MediaStream")}} for the stream created from the selected sources, getUserMedia()
returns a {{jsxref("promise")}} which is resolved with the {{domxref("MediaStream")}} once it's available.
The code that the video chat application would use might look something like this:
+The code that the video chat application would use might look something like this: -function handleCallButton(evt) { +```js +function handleCallButton(evt) { setStatusMessage("Calling..."); navigator.mediaDevices.getUserMedia({video: true, audio: true}) - .then(chatStream => { + .then(chatStream => { selfViewElem.srcObject = chatStream; - chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream)); + chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream)); setStatusMessage("Connected"); - }).catch(err => { + }).catch(err => { setStatusMessage("Failed to connect"); }); } -+``` -
This function starts by using a function called setStatusMessage()
to update a status display with the message "Calling...", indicating that a call is being attempted. It then calls getUserMedia()
, asking for a stream that has both video and audio tracks, then once that's been obtained, sets up a video element to show the stream coming from the camera as a "self view," then takes each of the stream's tracks and adds them to the WebRTC {{domxref("RTCPeerConnection")}} representing a connection to another user. After that, the status display is updated to say "Connected".
If getUserMedia()
fails, the catch
block runs. This uses setStatusMessage()
to update the status box to indicate that an error occurred.
The important thing here is that the getUserMedia()
call returns almost immediately, even if the camera stream hasn't been obtained yet. Even if the handleCallButton()
function has already returned to the code that called it, when getUserMedia()
has finished working, it calls the handler you provide. As long as the app doesn't assume that streaming has begun, it can just keep on running.
備註: You can learn more about this somewhat advanced topic, if you're interested, in the article Signaling and video calling. Code similar to this, but much more complete, is used in that example.
-To fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic.
+To fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic. -Let's talk about ordering pizza as an analogy. There are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished:
+Let's talk about ordering pizza as an analogy. There are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished: -With old-style callbacks, a pseudo-code representation of the above functionality might look something like this:
+With old-style [callbacks](/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#callbacks), a pseudo-code representation of the above functionality might look something like this: -chooseToppings(function(toppings) { +```js +chooseToppings(function(toppings) { placeOrder(toppings, function(order) { collectOrder(order, function(pizza) { eatPizza(pizza); }, failureCallback); }, failureCallback); -}, failureCallback);+}, failureCallback); +``` -
This is messy and hard to read (often referred to as "callback hell"), requires the failureCallback()
to be called multiple times (once for each nested function), with other issues besides.
Promises make situations like the above much easier to write, parse, and run. If we represented the above pseudo-code using asynchronous promises instead, we'd end up with something like this:
+Promises make situations like the above much easier to write, parse, and run. If we represented the above pseudo-code using asynchronous promises instead, we'd end up with something like this: -chooseToppings() +```js +chooseToppings() .then(function(toppings) { return placeOrder(toppings); }) @@ -110,346 +111,336 @@ tags: .then(function(pizza) { eatPizza(pizza); }) -.catch(failureCallback);+.catch(failureCallback); +``` -
This is much better — it is easier to see what is going on, we only need a single .catch()
block to handle all the errors, it doesn't block the main thread (so we can keep playing video games while we wait for the pizza to be ready to collect), and each operation is guaranteed to wait for previous operations to complete before running. We're able to chain multiple asynchronous actions to occur one after another this way because each .then()
block returns a new promise that resolves when the .then()
block is done running. Clever, right?
Using arrow functions, you can simplify the code even further:
+Using arrow functions, you can simplify the code even further: -chooseToppings() -.then(toppings => +```js +chooseToppings() +.then(toppings => placeOrder(toppings) ) -.then(order => +.then(order => collectOrder(order) ) -.then(pizza => +.then(pizza => eatPizza(pizza) ) -.catch(failureCallback);+.catch(failureCallback); +``` -
Or even this:
+Or even this: -chooseToppings() -.then(toppings => placeOrder(toppings)) -.then(order => collectOrder(order)) -.then(pizza => eatPizza(pizza)) -.catch(failureCallback);+```js +chooseToppings() +.then(toppings => placeOrder(toppings)) +.then(order => collectOrder(order)) +.then(pizza => eatPizza(pizza)) +.catch(failureCallback); +``` -
This works because with arrow functions () => x
is valid shorthand for () => { return x; }
.
You could even do this, since the functions just pass their arguments directly, so there isn't any need for that extra layer of functions:
+You could even do this, since the functions just pass their arguments directly, so there isn't any need for that extra layer of functions: -chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback);+```js +chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback); +``` -
This is not quite as easy to read, however, and this syntax might not be usable if your blocks are more complex than what we've shown here.
+This is not quite as easy to read, however, and this syntax might not be usable if your blocks are more complex than what we've shown here. -備註: You can make further improvements with async
/await
syntax, which we'll dig into in the next article.
At their most basic, promises are similar to event listeners, but with a few differences:
+At their most basic, promises are similar to event listeners, but with a few differences: -Promises are important to understand because most modern Web APIs use them for functions that perform potentially lengthy tasks. To use modern web technologies you'll need to use promises. Later on in the chapter, we'll look at how to write your own promise, but for now, we'll look at some simple examples that you'll encounter in Web APIs.
+Promises are important to understand because most modern Web APIs use them for functions that perform potentially lengthy tasks. To use modern web technologies you'll need to use promises. Later on in the chapter, we'll look at how to write your own promise, but for now, we'll look at some simple examples that you'll encounter in Web APIs. -In the first example, we'll use the fetch()
method to fetch an image from the web, the {{domxref("Body.blob", "blob()")}} method to transform the fetch response's raw body contents into a {{domxref("Blob")}} object, and then display that blob inside an {{htmlelement("img")}} element. This is very similar to the example we looked at in the first article of the series, but we'll do it a bit differently as we get you building your own promise-based code.
備註: The following example will not work if you just run it directly from the file (i.e. via a file://
URL). You need to run it through a local testing server, or use an online solution such as Glitch or GitHub pages.
First of all, download our simple HTML template and the sample image file that we'll fetch.
-Add a {{htmlelement("script")}} element at the bottom of the HTML {{htmlelement("body")}}.
-Inside your {{HTMLElement("script")}} element, add the following line:
+1. First of all, download our [simple HTML template](https://github.com/mdn/learning-area/blob/master/html/introduction-to-html/getting-started/index.html) and the [sample image file](https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/promises/coffee.jpg) that we'll fetch. +2. Add a {{htmlelement("script")}} element at the bottom of the HTML {{htmlelement("body")}}. +3. Inside your {{HTMLElement("script")}} element, add the following line: -let promise = fetch('coffee.jpg');+ ```js + let promise = fetch('coffee.jpg'); + ``` -
This calls the fetch()
method, passing it the URL of the image to fetch from the network as a parameter. This can also take an options object as an optional second parameter, but we are just using the simplest version for now. We are storing the promise object returned by fetch()
inside a variable called promise
. As we said before, this object represents an intermediate state that is initially neither success nor failure — the official term for a promise in this state is pending.
To respond to the successful completion of the operation whenever that occurs (in this case, when a {{domxref("Response")}} is returned), we invoke the .then()
method of the promise object. The callback inside the .then()
block runs only when the promise call completes successfully and returns the {{domxref("Response")}} object — in promise-speak, when it has been fulfilled. It is passed the returned {{domxref("Response")}} object as a parameter.
備註: The way that a .then()
block works is similar to when you add an event listener to an object using AddEventListener()
. It doesn't run until an event occurs (when the promise fulfills). The most notable difference is that a .then()
will only run once for each time it is used, whereas an event listener could be invoked multiple times.
We immediately run the blob()
method on this response to ensure that the response body is fully downloaded, and when it is available transform it into a Blob
object that we can do something with. The result of this is returned like so:
response => response.blob()+ We immediately run the `blob()` method on this response to ensure that the response body is fully downloaded, and when it is available transform it into a `Blob` object that we can do something with. The result of this is returned like so: -
which is shorthand for
+ ```js + response => response.blob() + ``` -function(response) { - return response.blob(); -}+ which is shorthand for -
Unfortunately, we need to do slightly more than this. Fetch promises do not fail on 404 or 500 errors — only on something catastrophic like a network failure. Instead, they succeed, but with the response.ok
property set to false
. To produce an error on a 404, for example, we need to check the value of response.ok
, and if false
, throw an error, only returning the blob if it is true
. This can be done like so — add the following lines below your first line of JavaScript.
let promise2 = promise.then(response => { - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - return response.blob(); - } -});-
Each call to .then()
creates a new promise. This is very useful; because the blob()
method also returns a promise, we can handle the Blob
object it returns on fulfillment by invoking the .then()
method of the second promise. Because we want to do something a bit more complex to the blob than just run a single method on it and return the result, we'll need to wrap the function body in curly braces this time (otherwise it'll throw an error).
Add the following to the end of your code:
+ ```js + let promise3 = promise2.then(myBlob => { -let promise3 = promise2.then(myBlob => { + }) + ``` -})-
Now let's fill in the body of the .then()
callback. Add the following lines inside the curly braces:
let objectURL = URL.createObjectURL(myBlob); -let image = document.createElement('img'); -image.src = objectURL; -document.body.appendChild(image);+ ```js + let objectURL = URL.createObjectURL(myBlob); + let image = document.createElement('img'); + image.src = objectURL; + document.body.appendChild(image); + ``` -
Here we are running the {{domxref("URL.createObjectURL()")}} method, passing it as a parameter the Blob
returned when the second promise fulfills. This will return a URL pointing to the object. Then we create an {{htmlelement("img")}} element, set its src
attribute to equal the object URL and append it to the DOM, so the image will display on the page!
If you save the HTML file you've just created and load it in your browser, you'll see that the image is displayed in the page as expected. Good work!
+If you save the HTML file you've just created and load it in your browser, you'll see that the image is displayed in the page as expected. Good work! -備註: You will probably notice that these examples are somewhat contrived. You could just do away with the whole fetch()
and blob()
chain, and just create an <img>
element and set its src
attribute value to the URL of the image file, coffee.jpg
. We did, however, pick this example because it demonstrates promises in a nice simple fashion, rather than for its real-world appropriateness.
Something is missing — currently, there is nothing to explicitly handle errors if one of the promises fails (rejects, in promise-speak). We can add error handling by running the .catch()
method off the previous promise. Add this now:
let errorCase = promise3.catch(e => { +```js +let errorCase = promise3.catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); -});+}); +``` -
To see this in action, try misspelling the URL to the image and reloading the page. The error will be reported in the console of your browser's developer tools.
+To see this in action, try misspelling the URL to the image and reloading the page. The error will be reported in the console of your browser's developer tools. -This doesn't do much more than it would if you just didn't bother including the .catch()
block at all, but think about it — this allows us to control error handling exactly how we want. In a real app, your .catch()
block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever.
備註: You can see our version of the example live (see the source code also).
-This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then()
blocks (and also .catch()
blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub):
fetch('coffee.jpg') -.then(response => { +```js +fetch('coffee.jpg') +.then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }) -.then(myBlob => { +.then(myBlob => { let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) -.catch(e => { +.catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); -});+}); +``` -
Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then()
block's callback function.
備註: .then()
/.catch()
blocks in promises are basically the async equivalent of a try...catch
block in sync code. Bear in mind that synchronous try...catch
won't work in async code.
There was a lot to cover in the above section, so let's go back over it quickly to give you a short guide that you can bookmark and use to refresh your memory in the future. You should also go over the above section again a few more time to make sure these concepts stick.
+There was a lot to cover in the above section, so let's go back over it quickly to give you a [short guide that you can bookmark](/en-US/docs/Learn/JavaScript/Asynchronous/Promises#promise_terminology_recap) and use to refresh your memory in the future. You should also go over the above section again a few more time to make sure these concepts stick. -.then()
block onto the end of the promise chain. The callback function inside the .then()
block will contain the promise's return value..catch()
block onto the end of the promise chain.The above example showed us some of the real basics of using promises. Now let's look at some more advanced features. For a start, chaining processes to occur one after the other is all fine, but what if you want to run some code only after a whole bunch of promises have all fulfilled?
+## Running code in response to multiple promises fulfilling -You can do this with the ingeniously named Promise.all()
static method. This takes an array of promises as an input parameter and returns a new Promise
object that will fulfil only if and when all promises in the array fulfil. It looks something like this:
Promise.all([a, b, c]).then(values => { +You can do this with the ingeniously named [`Promise.all()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) static method. This takes an array of promises as an input parameter and returns a new `Promise` object that will fulfil only if and when _all_ promises in the array fulfil. It looks something like this: + +```js +Promise.all([a, b, c]).then(values => { ... -});+}); +``` -
If they all fulfil, the chained .then()
block's callback function will be passed an array containing all those results as a parameter. If any of the promises passed to Promise.all()
reject, the whole block will reject.
This can be very useful. Imagine that we’re fetching information to dynamically populate a UI feature on our page with content. In many cases, it makes sense to receive all the data and only then show the complete content, rather than displaying partial information.
+This can be very useful. Imagine that we’re fetching information to dynamically populate a UI feature on our page with content. In many cases, it makes sense to receive all the data and only then show the complete content, rather than displaying partial information. -Let's build another example to show this in action.
+Let's build another example to show this in action. -Download a fresh copy of our page template, and again put a <script>
element just before the closing </body>
tag.
Download our source files (coffee.jpg, tea.jpg, and description.txt), or feel free to substitute your own.
-In our script, we'll first define a function that returns the promises we want to send to Promise.all()
. This would be easy if we just wanted to run the Promise.all()
block in response to three fetch()
operations completing. We could just do something like: