非同期 / 待機

Barbara Streisand
リリース: 2024-10-10 06:24:30
オリジナル
809 人が閲覧しました

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 サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!