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

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

Patricia Arquette
Patricia Arquetteオリジナル
2024-09-26 08:20:02364ブラウズ

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 までご連絡ください。