首頁 > web前端 > js教程 > 主體

異步/等待

Barbara Streisand
發布: 2024-10-10 06:24:30
原創
811 人瀏覽過

async / await

異步/等待

與 Promise 相比,async/await 是一種更新的非同步程式碼編寫方式。 async/await 的主要優點是提高了可讀性並避免了承諾鏈。 Promise 可能會變得很長、難以閱讀,並且可能包含難以調試的深層嵌套回呼。

例子

回想一下我們之前的獲取。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error))
  .finally(() => console.log('All done'));
登入後複製

使用 async/await,程式碼可以重構為如下所示:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  } finally {
    console.log('All done');
  }
}

fetchData();
登入後複製

雖然可能多了幾行程式碼,但這個版本更容易閱讀,因為它類似於普通的同步函數。此外,如果 .then() 語句內的函數更複雜,則可讀性和可調試性將受到更大的影響。 async/await 範例更加清晰。

範例 2:從餐廳訂餐

async/await 的結構

async/await 函數有兩個基本部分:async 和await。 async 關鍵字加在函數宣告前,await 用於非同步任務開始時。

讓我們以從餐廳點餐的例子來說明這一點:

// Simulate the order process with async/await
async function foodOrder() {
  console.log("Ordering food...");
  await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds for food to be prepared
  return "Your food is ready!";
}

// Simulate the eating process
function eatFood(order) {
  console.log(order); // This logs "Your food is ready!"
  console.log("Enjoying the meal!");
}

// Simulate continuing the conversation
function continueConversation() {
  console.log("While waiting, you continue chatting with friends...");
}

async function orderFood() {
  console.log("You've arrived at the restaurant.");
  const order = await foodOrder(); // Place the order and wait for it to be ready
  continueConversation(); // Chat while waiting
  eatFood(order); // Eat the food once it arrives
}

orderFood();
登入後複製

輸出將是

You've arrived at the restaurant.
Ordering food...
While waiting, you continue chatting with friends...
Your food is ready!
Enjoying the meal!
登入後複製

以上是異步/等待的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!