JS中的async/await怎么用?有什么作用?

async/await 是 JavaScript 中處理異步操作的語法糖,本質是對 promise封裝,使代碼更清晰易維護。1. async 函數通過自動將返回值包裝成 promise 來聲明異步函數;2. await 用于暫停 async 函數執行,直到 promise 被解決,只能在 async 函數中使用;3. 推薦用 try/catch 捕獲錯誤,并行任務可結合 promise.all 使用;4. 相比 promise.then() 鏈,async/await 結構更清晰、錯誤處理更直觀;5. 注意避免濫用 await 影響性能,調用 async 函數需通過 .then() 或 await 處理返回值。掌握這些要點后即可熟練應用 async/await 編寫異步代碼。

JS中的async/await怎么用?有什么作用?

在JavaScript中,async/await 是處理異步操作的一種更清晰、更簡潔的寫法。它本質上是對 Promise 的封裝,讓你可以用同步的方式寫異步代碼,提升可讀性和可維護性。


什么是 async 函數?

async 是一個關鍵字,用來聲明一個函數是異步函數。它會自動將函數的返回值包裝成一個 Promise。

async function getData() {   return 'Hello'; }  getData().then(data => console.log(data)); // 輸出 Hello

上面這個例子中,即使函數直接返回了一個字符串,它也會被自動轉換為一個 resolved 狀態的 Promise。

關鍵點:

  • async 函數內部可以使用 await
  • 返回值總是 Promise,不管有沒有顯式返回

await 的作用和用法

await 只能在 async 函數里使用,它的作用是“暫停”當前異步函數的執行,直到一個 Promise 被解決(resolved 或 rejected)。

舉個實際的例子:

async function fetchUser() {   const response = await fetch('https://api.example.com/user');   const data = await response.JSon();   console.log(data); }

這段代碼看起來像同步代碼,但實際上是異步的。await 讓你不用再寫 .then() 鏈條,邏輯也更清晰。

常見寫法建議:

  • 使用 try/catch 捕獲錯誤:
    async function fetchUser() {   try {     const response = await fetch('https://api.example.com/user');     const data = await response.json();     console.log(data);   } catch (error) {     console.error('請求失敗:', error);   } }
  • 如果多個異步任務不依賴彼此,可以并行執行:
    async function loadBoth() {   const [res1, res2] = await Promise.all([fetch(url1), fetch(url2)]); }

async/await 相比 Promise 有什么優勢?

雖然 async/await 底層還是基于 Promise 實現的,但它有幾個明顯的好處:

  • 代碼結構更清晰:避免了回調地獄和長鏈 .then()
  • 錯誤處理更方便:可以用熟悉的 try/catch 來統一捕獲異常
  • 邏輯順序更直觀:每一行按順序執行,不需要來回跳轉理解流程

比如對比下面兩段代碼:

Promise 寫法:

fetchData()   .then(data => process(data))   .then(result => console.log(result))   .catch(err => console.error(err));

async/await 寫法:

async function handle() {   try {     const data = await fetchData();     const result = await process(data);     console.log(result);   } catch (err) {     console.error(err);   } }

兩者功能一樣,但后者更容易閱讀和維護。


常見注意事項

雖然 async/await 很好用,但也有些細節容易忽略:

  • 不要在循環或高頻函數中濫用 await,否則會影響性能
  • 注意函數返回的是 Promise,調用時要記得用 .then() 或再加 await
  • 錯誤處理不能省略,否則異常會被靜默吞掉

基本上就這些。掌握這幾個點之后,就能比較熟練地在項目中使用 async/await 了。

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享