「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > 非同期 / 待機

非同期 / 待機

2024 年 11 月 1 日に公開
ブラウズ:418

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!
リリースステートメント この記事は次の場所に転載されています: https://dev.to/wolfmath/async-await-13bn?1 侵害がある場合は、[email protected] に連絡して削除してください。
最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3