如何在 JavaScript 中建立非同步函式?
JavaScript 非同步函式是在獨立於程式主流程執行的函式。這允許程式在非同步函式執行時繼續執行其他程式碼。`async` 用於宣告非同步函式,該函式非同步執行;`await` 用於暫停函式的執行,直到完成特定的非同步任務。
建立非同步函式的方法
使用 async 關鍵字
建立非同步函式最簡單的方法是在函式宣告前使用 `async` 關鍵字。請參見以下語法:
語法
async function fetchData() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); }
在這個例子中,`fetchData` 函式使用 `await` 關鍵字等待從伺服器獲取資料,然後將其記錄到控制檯。
示例
以下是如何在 JavaScript 中使用非同步函式從伺服器獲取資料並在 HTML 頁面上顯示資料的示例:
<!DOCTYPE html> <html> <head> <title>async</title> </head> <body> <p>Click below button to see the result</p> <button id="get-data">Get</button> <div id="data-box"></div> <script> // Asynchronous function to fetch data async function fetchData() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/3'); const data = await response.json(); return data; } // Add click event listener to the button const button = document.getElementById('get-data'); button.addEventListener('click', async () => { // Call the asynchronous function const data = await fetchData(); // Use the data to update the HTML const dataBox = document.getElementById('data-box'); dataBox.innerHTML = `<p>Id: ${data.id}</p><p>Title: ${data.title}</p>`; }); </script> </body> </html>
在這個例子中,我們有一個 ID 為 "get-button" 的 HTML 按鈕和一個 ID 為 "data-box" 的 div 容器。我們向按鈕添加了一個事件監聽器,因此當單擊它時,它會呼叫非同步函式 `fetchData`,該函式使用 `fetch` API 從伺服器檢索資料。資料返回後,它用於使用檢索到的資料的標題和已完成狀態更新 ID 為 "data-box" 的 div 容器的 HTML 內容。
注意 - 以上程式碼的輸出可能會隨時間而變化,因為資料來自外部 API。
使用 Promise
建立非同步函式的另一種方法是使用 Promise 物件。Promise 是一個表示非同步操作最終完成(或失敗)及其結果值的 物件。
語法
function fetchData() { return new Promise((resolve, reject) => { fetch('yoururl.com') .then(response => response.json()) .then(data => resolve(data)) .catch(error => reject(error)); }); }
在語法中,`fetchData` 函式返回一個新的 Promise,該 Promise 從伺服器獲取資料,並使用資料解析或使用錯誤拒絕。`then` 和 `catch` 方法用於處理 Promise 的解析或拒絕。
示例
以下是如何在 JavaScript 中使用 Promise 從伺服器獲取資料並在 HTML 頁面上顯示資料的示例:
<html> <body> <p>Click below button to see the result</p> <button id="get-button">Get</button> <div id="data-box"></div> <script> // Async promise function to fetch data function fetchData() { return new Promise((resolve, reject) => { fetch('https://jsonplaceholder.typicode.com/todos/3') .then(response => response.json()) .then(data => resolve(data)) .catch(error => reject(error)); }); } // Add click event listener to the button const button = document.getElementById('get-button'); button.addEventListener('click', () => { // Call the promise fetchData() .then(data => { // Use the data to update the HTML const dataBox = document.getElementById('data-box'); dataBox.innerHTML = `<p>Id: ${data.id}</p><p>Status: ${data.completed}</p>`; }) .catch(error => console.log(error)); }); </script> </body> </html>
在這個例子中,我們有一個 ID 為 "get-button" 的 HTML 按鈕和一個 ID 為 "data-box" 的 div 容器。我們向按鈕添加了一個事件監聽器,因此當單擊它時,它會呼叫函式 `fetchData`,該函式使用 `fetch` API 從伺服器檢索資料並返回一個 Promise。Promise 解析後,它用於使用檢索到的資料的 ID 和已完成項更新 ID 為 "data-box" 的 div 容器的 HTML 內容。如果 Promise 被拒絕,它會在控制檯中記錄錯誤。
注意 - 以上程式碼的輸出可能會隨時間而變化,因為資料來自外部 API。
使用 async/await 與 Promise.all
Promise.all 方法返回一個 Promise,當作為可迭代物件傳遞的所有 Promise 都已解析時,該 Promise 將解析;如果第一個傳遞的 Promise 被拒絕,則該 Promise 將被拒絕,並使用拒絕的原因。
語法
async function fetchData() { const response = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/todos/1'), fetch('https://jsonplaceholder.typicode.com/todos/2') ]); const data = await Promise.all(response.map(res => res.json())); console.log(data); }
在這個例子中,`fetchData` 函式使用 `Promise.all` 方法從伺服器獲取多個數據,並使用 `await` 關鍵字等待所有響應,然後將資料記錄到控制檯。
示例
以下是如何在 JavaScript 中使用 async/await 與 Promise.all 從伺服器獲取多個數據並在 HTML 頁面上顯示資料的示例:
<html> <body> <p>Click below button to see the result</p> <button id="get-button">Get</button> <div id="data-box"></div> <script> // Asynchronous function to fetch data async function fetchData() { const response = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/todos/1'), fetch('https://jsonplaceholder.typicode.com/todos/2') ]); const data = await Promise.all(response.map(res => res.json())); return data; } // Add click event listener to the button const fetchButton = document.getElementById('get-button'); fetchButton.addEventListener('click', async () => { // Call the async function const data = await fetchData(); // Use the data to update the HTML const dataBox = document.getElementById('data-box'); dataBox.innerHTML = ` <p>Id 1: ${data[0].id}</p> <p>Title 1: ${data[0].title}</p> <p>Status 1: ${data[0].completed}</p> <p>Id 2: ${data[1].id}</p> <p>Title 2: ${data[1].title}</p> <p>Status 2: ${data[1].completed}</p> `; }); </script> </body> </html>
在這個例子中,我們有一個 ID 為 "get-button" 的 HTML 按鈕和一個 ID 為 "data-box" 的 div 容器。我們向按鈕添加了一個事件監聽器,因此當單擊它時,它會呼叫非同步函式 `fetchData`,該函式使用 `fetch` API 和 `Promise.all` 方法從伺服器檢索多個數據。現在它使用 `await` 關鍵字等待所有響應,然後返回資料,然後使用檢索到的資料的 id、標題和已完成項更新 ID 為 "data-box" 的 div 容器的 HTML 內容。
注意 - 以上程式碼的輸出可能會隨時間而變化,因為資料來自外部 API。
結論
JavaScript 提供了幾種建立非同步函式的方法,包括使用 `async` 關鍵字、Promise 物件以及 async/await 與 Promise.all。每種方法都有其自身的優點和用例。`async` 關鍵字和 `await` 關鍵字用於執行需要很長時間才能完成的任務,例如從伺服器獲取資料等。