ホームページ ウェブフロントエンド jsチュートリアル 非同期 JavaScript - 混乱を解消する

非同期 JavaScript - 混乱を解消する

Sep 26, 2024 am 08:20 AM

Asynchronous JavaScript - Get Confusions Cleared

注: トピック全体を順を追って説明しましたが、質問がある場合や説明が必要な場合は、任意のセクションに進んでください。

非同期 JavaScript について説明する前に、同期 JavaScript とは何か、また、なぜ JavaScript コードを記述するのに非同期の方法が必要なのかを理解することが重要です。

同期JavaScriptとは何ですか?

同期プログラミングでは、タスクが順番に順番に実行されます。次のタスクは、現在のタスクが終了した後にのみ開始できます。 1 つのタスクに時間がかかると、他のすべてのタスクも待たなければなりません。

食料品店で列に並んで待つようなものだと考えてください: 前の人がたくさんの商品を持っていて、チェックアウトに時間がかかる場合は、それらが終わるまで順番を待たなければなりません続行する前に。

console.log("Start cooking");

for (let i = 0; i < 5; i++) {
  console.log("Cooking dish " + (i + 1));
}

console.log("Finish cooking");
ログイン後にコピー

以下のことが起こります:

  1. 「調理開始」と印刷されます。

  2. その後、ループに入り、「料理 X」を次々と出力します。

  3. ループが完了した後でのみ、「調理終了」と表示されます。

この場合、コードは順番に実行され、現在のタスク (各料理の調理) が完了するまでは何も起こりません。ある料理を作るのに 10 分かかったと想像してみてください。他の料理はすべてその料理が終わるまで待たなければなりません。

非同期JavaScriptとは何ですか?

非同期プログラミングでは、タスクを開始でき、タスクがまだ実行されている間 (サーバーからのデータを待っているなど)、他のタスクは実行を続けることができます。あるタスクが完了するまで待ってから別のタスクを開始する必要はありません。

レストランで注文するようなものだと考えてください: 食べ物を注文し、準備ができている間、友達と話したり、携帯電話をチェックしたりすることができます。料理が完成したら、ウェイターがそれを持ってきてくれます。

非同期コードの例:

console.log("Start cooking");

setTimeout(() => {
  console.log("Cooking is done!");
}, 3000); // Simulate a task that takes 3 seconds

console.log("Prepare other things while waiting");
ログイン後にコピー

以下のことが起こります:

  1. 「調理開始」と印刷されます。

  2. setTimeout 関数は 3 秒のタイマーを開始します。ただし、JavaScript は待つ代わりに、すぐに次の行に進みます。

  3. 「待っている間に他のものを準備してください」と印刷されます。

  4. 3 秒後、タイマーが完了し、「調理が完了しました!」と表示されます。


非同期 JavaScript を記述するには主に次の 3 つの方法があります。

  1. コールバック

  2. 約束

  3. 非同期/待機

これらは、JavaScript で非同期コードを処理するための主なアプローチです。

コールバック

JavaScript の コールバック関数 は、別の関数に引数として渡す関数です。基本的な考え方は、関数を引数として別の関数に渡すか定義するというもので、渡された関数は「コールバック関数」と呼ばれます。コールバックは、特定のタスクの完了後、多くの場合、サーバーからのデータのフェッチなどの非同期タスクの後に呼び出されます (または「呼び出されます」)。

これにより、メイン関数はタスクの終了を待たずに他の作業を続行できるようになります。タスクが完了すると、結果を処理するためにコールバックがトリガーされます。

function mainFunc(callback){
  console.log("this is set before setTimeout")
  callback()
  console.log("this is set after setTimeout")
}

function cb(){
  setTimeout(()=>{
    console.log("This is supposed to be painted after 3 second")
  },3000)
}

mainFunc(cb)
ログイン後にコピー

このコードは、JavaScript の コールバック の概念を示しています。仕組みは次のとおりです:

  1. mainFunc は、callback 関数を引数として受け取ります。

  2. mainFunc 内では、callback がすぐに実行されますが、callback 自体 (cb 関数) には setTimeout が含まれているため、console.log が実行後に実行されるようにスケジュールされます。 3 秒。

  3. その間、mainFunc は実行を継続し、コールバックの呼び出しの前後にメッセージを出力します。

  4. 3 秒後、コールバック内の setTimeout が終了し、遅延メッセージが出力されます。

これは、main 関数が非同期操作 (コールバックの 3 秒の遅延) の完了を待たずにタスクを続行する方法を示しています。

コールバック地獄とは何ですか?いつ起こりますか?

コールバック地獄 とは、複数のコールバックが管理不能な方法で相互にネストされ、コードの読み取り、保守、デバッグが困難になる JavaScript の状況を指します。これは多くの場合、入れ子になった関数のピラミッドのように見えます。各非同期操作は前の操作の完了に依存し、深く入れ子になったコールバックにつながります。

コールバック 地獄は通常、順番に実行する必要がある複数の非同期タスクがあり、各タスクが前のタスクの結果に依存する場合に発生します。タスクが追加されると、コードはますますインデントされ、従うのが難しくなり、その結果、乱雑で複雑な構造になります。

getData((data) => {
  processData(data, (processedData) => {
    saveData(processedData, (savedData) => {
      notifyUser(savedData, () => {
        console.log("All tasks complete!");
      });
    });
  });
});
ログイン後にコピー

Here, each task is dependent on the previous one, leading to multiple levels of indentation and difficult-to-follow logic. If there’s an error at any point, handling it properly becomes even more complex.

To rescue you from callback hell, modern JavaScript provides solutions like:

  1. Promises – which flatten the code and make it more readable.

  2. Async/Await – which simplifies chaining asynchronous operations and makes the code look synchronous.

Promises

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its result. It’s like a promise you make in real life: something may not happen immediately, but you either fulfill it or fail to fulfill it.

In JavaScript, Promises allow you to write asynchronous code in a cleaner way, avoiding callback hell. A Promise is created using the new Promise syntax, and it takes a function (which is constructor function) with two parameters: resolve (if the task is successful) and reject (if it fails).

const myPromise = new Promise((resolve, reject) => {
  // Simulating an asynchronous task like fetching data
  const success = true; // Change to false to simulate failure

  setTimeout(() => {
    if (success) {
      resolve("Task completed successfully!"); // Success
    } else {
      reject("Task failed!"); // Failure
    }
  }, 2000); // 2-second delay
});
ログイン後にコピー

Here:

  • The promise simulates a task that takes 2 seconds.

  • If the task is successful (success is true), it calls resolve with a message.

  • If it fails (success is false), it calls reject with an error message.

How to handle a Promise

To handle the result of a Promise, we use two methods:

  • .then() for a successful result (when the Promise is fulfilled).

  • .catch() for an error (when the Promise is rejected).

myPromise
  .then((message) => {
    console.log(message); // "Task completed successfully!" (if resolve was called)
  })
  .catch((error) => {
    console.log(error); // "Task failed!" (if reject was called)
  });
ログイン後にコピー

Chaining in Promises

Promises allow you to chain asynchronous operations using the .then() method, which makes the code more linear and easier to follow. Each .then() represents a step in the asynchronous process. The .catch() method allows you to centralize error handling at the end of the promise chain, making it more organized.

fetchData()
  .then(data => processData1(data))
  .then(result1 => processData2(result1))
  .then(result2 => processData3(result2))
  .catch(error => handleError(error));
ログイン後にコピー

Promises promote a more readable and maintainable code structure by avoiding deeply nested callbacks. The chaining and error-handling mechanisms contribute to a clearer and more organized codebase.

// Callback hell
fetchData1(data1 => {
  processData1(data1, result1 => {
    fetchData2(result1, data2 => {
      processData2(data2, result2 => {
        fetchData3(result2, data3 => {
          processData3(data3, finalResult => {
            console.log("Final result:", finalResult);
          });
        });
      });
    });
  });
});

// Using Promises
fetchData1()
  .then(result1 => processData1(result1))
  .then(data2 => fetchData2(data2))
  .then(result2 => processData2(result2))
  .then(data3 => fetchData3(data3))
  .then(finalResult => {
    console.log("Final result:", finalResult);
  })
  .catch(error => handleError(error));
ログイン後にコピー

finally Method

The finally method is used to execute code, regardless of whether the Promise is resolved or rejected.

myPromise
  .then((data) => {
    console.log("Data:", data);
  })
  .catch((error) => {
    console.error("Error:", error);
  })
  .finally(() => {
    console.log("Finally block"); // This runs no matter what
  });
ログイン後にコピー

If the promise is fulfilled (i.e., it successfully gets data), the .then() method will be executed. On the other hand, if the promise encounters an error, the .catch() method will be called to handle the error. However, the .finally() method has no such condition—it will always be executed, regardless of whether the promise was resolved or rejected. Whether the .then() or .catch() is triggered, the .finally() block will definitely run at the end.

It's useful for cleaning up resources, stopping loading indicators, or doing something that must happen after the promise completes, regardless of its result.

JavaScript Promise Methods

JavaScript provides several Promise methods that make working with asynchronous tasks more flexible and powerful. These methods allow you to handle multiple promises, chain promises, or deal with various outcomes in different ways

Method Description
all (iterable) Waits for all promises to be resolved or any one to be rejected.
allSettled (iterable) Waits until all promises are either resolved or rejected.
any (iterable) Returns the promise value as soon as any one of the promises is fulfilled.
race (iterable) Waits until any of the promises is resolved or rejected.
reject (reason) Returns a new promise object that is rejected for the given reason.
resolve (value) Returns a new promise object that is resolved with the given value.

Promise.all() - Parallel Execution

You can use Promise.all() to execute multiple asynchronous operations concurrently and handle their results collectively.

This method takes an array of promises and runs them in parallel which returns a new Promise. This new Promise fulfils with an array of resolved values when all the input Promises have fulfilled, or rejects with the reason of the first rejected Promise.

Copy code
const promise1 = Promise.resolve(10);
const promise2 = Promise.resolve(20);
const promise3 = Promise.resolve(30);

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // [10, 20, 30]
});
ログイン後にコピー

If one of the promises rejects, the whole Promise.all() will reject:

const promise1 = Promise.resolve(10);
const promise2 = Promise.reject("Error!");

Promise.all([promise1, promise2])
  .then((values) => {
    console.log(values);
  })
  .catch((error) => {
    console.log(error); // "Error!"
  });
ログイン後にコピー

Promise.allSettled()

This method takes an array of promises and returns a new promise after all of them finish their execution, whether they succeed or fail. Unlike Promise.all(), it doesn't fail if one promise fails. Instead, it waits for all the promises to complete and gives you an array of results that show if each one succeeded or failed.

It’s useful when you want to know the result of every promise, even if some fail.

const promise1 = Promise.resolve("Success!");
const promise2 = Promise.reject("Failure!");

Promise.allSettled([promise1, promise2]).then((results) => {
  console.log(results);
  // [{ status: 'fulfilled', value: 'Success!' }, { status: 'rejected', reason: 'Failure!' }]
});
ログイン後にコピー

Promise.any()

Promise.any() takes an array of promises and returns a promise that resolves as soon as any one promise resolves. If all input Promises are rejected, then Promise.any() rejects with an AggregateError containing an array of rejection reasons.

It’s useful when you need just one successful result from multiple promises.

const promise1 = fetchData1();
const promise2 = fetchData2();
const promise3 = fetchData3();

Promise.any([promise1, promise2, promise3])
  .then((firstFulfilledValue) => {
    console.log("First promise fulfilled with:", firstFulfilledValue);
  })
  .catch((allRejectedReasons) => {
    console.error("All promises rejected with:", allRejectedReasons);
  });
ログイン後にコピー

Promise.race()

This method takes an array of promises and returns a new promise that resolves or rejects as soon as the first promise settles (either resolves or rejects).

It’s useful when you want the result of the fastest promise, ignoring the others.

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, "First"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 200, "Second"));

Promise.race([promise1, promise2]).then((value) => {
  console.log(value); // "First" (because promise1 resolves first)
});
ログイン後にコピー

Promise.resolve()

This method immediately resolves a promise with a given value. It’s useful for creating a promise that you already know will be fulfilled.

const resolvedPromise = Promise.resolve("Resolved!");
resolvedPromise.then((value) => {
  console.log(value); // "Resolved!"
});
ログイン後にコピー

Promise.reject()

This method immediately rejects a promise with a given error or reason. It’s useful for creating a promise that you know will fail.

const rejectedPromise = Promise.reject("Rejected!");
rejectedPromise.catch((error) => {
  console.log(error); // "Rejected!"
});
ログイン後にコピー

I hope you have no confusion regarding promises after carefully reading this explanation of promises. Now, it’s time to move on Async/Await.

Async/Await

async / await is a modern way to handle asynchronous operations in JavaScript, introduced in ES2017 (ES8). It’s built on top of Promises but provides a cleaner and more readable syntax, making asynchronous code look and behave more like synchronous code. This makes it easier to understand and debug.

How async and await Work

When you declare a function with the async keyword, it always returns a Promise. Even if you don't explicitly return a promise, JavaScript wraps the return value inside a resolved promise.

The await keyword can only be used inside an async function. It makes JavaScript wait for the promise to resolve before moving on to the next line of code. It “pauses” the execution of the function, allowing you to handle asynchronous tasks more sequentially, just like synchronous code.

Let’s look at a simple example to see how this works:

async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log("Data:", data);
  } catch (error) {
    console.error("Error fetching data:", error);
  } finally {
    console.log("Fetch operation complete");
  }
}

fetchData();
ログイン後にコピー

How it works:

  1. async function: Since fetchData function is marked as async, that means it returns a promise.

  2. await fetch(): The await pauses the execution of the function until the promise returned by fetch() resolves. It then continues with the next line after the promise is resolved.

  3. try/catch: We use a try/catch block to handle any potential errors during the async operation.

  4. finally: Regardless of success or failure, the finally block will execute.

Why Use async / await?

With async/await, your code becomes more readable and flows more naturally. This makes it easier to follow the logic, especially when dealing with multiple asynchronous operations.

Compare this to handling promises with .then():

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => {
    console.log("Data:", data);
  })
  .catch(error => {
    console.error("Error fetching data:", error);
  })
  .finally(() => {
    console.log("Fetch operation complete");
  });
ログイン後にコピー

The async/await version looks cleaner and easier to understand. async/await helps avoid the nesting of callbacks or .then() chains, making your code more linear and easier to follow.

Example with Multiple await

You can also handle multiple asynchronous tasks in a sequence without needing to chain promises.

async function processOrders() {
  const user = await getUserDetails();  // Waits for user details
  const orders = await getOrders(user.id);  // Waits for orders
  console.log("Orders:", orders);
}

processOrders();
ログイン後にコピー

In this example, the function waits for each task to finish before moving on to the next, just like how synchronous code would behave.

Parallel Execution with Promise.all() and async/await

If you want to perform multiple asynchronous operations at the same time (in parallel), you can still use Promise.all() with async/await:

async function getAllData() {
  const [user, orders] = await Promise.all([getUserDetails(), getOrders()]);
  console.log("User:", user);
  console.log("Orders:", orders);
}
ログイン後にコピー

Here, both getUserDetails() and getOrders() run simultaneously, and the function waits for both to finish before logging the results.

Conclusion

In JavaScript, handling asynchronous operations has evolved over time, offering different tools to make code more manageable and efficient. Callbacks were the first approach, but as the complexity of code grew, they often led to issues like "callback hell." Promises came next, providing a cleaner, more structured way to manage async tasks with .then() and .catch(), improving readability and reducing nesting.

Finally, async/await was introduced as a modern syntax built on promises, making asynchronous code look more like synchronous code. It simplifies the process even further, allowing for easier-to-read, more maintainable code. Each of these techniques plays an important role in JavaScript, and mastering them helps you write more efficient, clear, and robust code.

Understanding when to use each method—callbacks for simple tasks, promises for structured handling, and async/await for readable, scalable async code—will empower you to make the best choices for your projects.

My Last Words

I used to get confused by the concept of promises, especially the different methods of promises. Callbacks were a big challenge for me because the syntax always seemed very confusing. So, I read various sources online, including chatbots, to come up with this description. To be honest, chatbots don’t always provide a straight and understandable answer. So, I didn’t just copy and paste from different places—I simplified everything so that it can serve as a clear note for me and for anyone else who has difficulty grasping these concepts. I hope this note leaves you with zero confusion.

以上が非同期 JavaScript - 混乱を解消するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

javascriptの分解:それが何をするのか、なぜそれが重要なのか javascriptの分解:それが何をするのか、なぜそれが重要なのか Apr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

JavaScriptの進化:現在の傾向と将来の見通し JavaScriptの進化:現在の傾向と将来の見通し Apr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

JavaScriptエンジン:実装の比較 JavaScriptエンジン:実装の比較 Apr 13, 2025 am 12:05 AM

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

JavaScript:Web言語の汎用性の調査 JavaScript:Web言語の汎用性の調査 Apr 11, 2025 am 12:01 AM

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

Python vs. JavaScript:学習曲線と使いやすさ Python vs. JavaScript:学習曲線と使いやすさ Apr 16, 2025 am 12:12 AM

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合) next.jsを使用してマルチテナントSaaSアプリケーションを構築する方法(フロントエンド統合) Apr 11, 2025 am 08:22 AM

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します

C/CからJavaScriptへ:すべてがどのように機能するか C/CからJavaScriptへ:すべてがどのように機能するか Apr 14, 2025 am 12:05 AM

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合) next.jsを使用してマルチテナントSaaSアプリケーションを構築する(バックエンド統合) Apr 11, 2025 am 08:23 AM

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます

See all articles