# [學習筆記] Javascript async await ### :small_blue_diamond: async await 的用途? async/await 是一個 JavaScript 中用於處理異步操作的語法糖(syntactic sugar),它建立在 Promise 的基礎上,提供了更簡潔和可讀性更高的方式來編寫異步代碼。 使用 async/await,你可以將異步操作的邏輯寫成看起來像同步代碼的形式,而不需要嵌套的回調函數或鏈式的 .then() 語法。這使得代碼的結構更加線性和易於理解。 * **async** 被用於聲明一個函數是異步函數,這意味著函數內部可能包含 await 表達式。異步函數總是返回一個 Promise 對象。 * **await** 則用於等待一個 Promise 對象的解析(或拒絕),並在該 Promise 解析後繼續執行下面的代碼。在 await 表達式後的代碼將被包裹在一個 Promise 中返回。 <br> ✎ 假設我們有一個函數 getData,它模擬了一個異步操作,例如從服務器獲取數據: ```javascript! function getData() { return new Promise(resolve => { setTimeout(() => { resolve('這是從服務器獲取的數據'); }, 2000); }); } ``` <br> ✎ 使用 Promise,我們可以這樣使用它: ```javascript! getData().then(result => { console.log(result); }).catch(error => { console.log(error); }); ``` <br> ✎ 使用 async/await 重寫上面的代碼,看看它是如何簡化的: ```javascript! async function fetchData() { try { const result = await getData(); console.log(result); } catch (error) { console.log(error); } } fetchData(); ``` :::warning 使用 async/await,我們將 fetchData 函數聲明為異步函數,並使用 await 關鍵字等待 getData 函數返回的 Promise。 然後,我們使用常規的變數賦值將結果存儲在 result 中,並可以直接使用它。在 try/catch 塊中,我們可以捕獲錯誤並進行處理。 這個例子展示了 async/await 如何使異步代碼的編寫更加直觀和類似於同步代碼。 我們可以使用常規的控制流結構(例如 if 語句和 try/catch 塊)來處理異步操作的結果和錯誤。 :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up