ホームページ  >  記事  >  ウェブフロントエンド  >  非同期 / 待機

非同期 / 待機

Barbara Streisand
Barbara Streisandオリジナル
2024-10-10 06:24:30811ブラウズ

async / await

非同期 / 待機

async / await は、Promise と比較して非同期コードを記述する新しい方法です。 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 という 2 つの重要な部分があります。 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。