"Si un ouvrier veut bien faire son travail, il doit d'abord affûter ses outils." - Confucius, "Les Entretiens de Confucius. Lu Linggong"
Page de garde > La programmation > 在JavaScript中如何并发运行异步操作并正确处理错误?

在JavaScript中如何并发运行异步操作并正确处理错误?

Publié le 2025-05-02
Parcourir:417

How Can I Run Asynchronous Operations Concurrently in JavaScript with Proper Error Handling?

Concurrent Await Operation Execution

The code snippet in question encounters an issue when performing asynchronous operations:

<pre>
const value1 = await getValue1Async();
const value2 = await getValue2Async();
</pre>

This implementation sequentially waits for the completion of each operation before starting the next. To enable concurrent execution, a modified approach is required.

Promise Decomposition and Separate Await

The first solution presented attempts to address this by obtaining the promises for each operation, then waiting on them separately:

<pre>
const p1 = getValue1Async();
const p2 = getValue2Async();
const value1 = await p1;
const value2 = await p2;
</pre>

While this method does run both operations in parallel, it does not handle rejection properly if both promises reject. It also waits for the first operation to complete before starting the second, which is inefficient.

Promise.all Solution

To resolve these issues, the Promise.all function can be employed:

<pre>
const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]);
</pre>

Promise.all takes an array of promises and returns a single promise that resolves when all of the input promises have resolved or rejected. This approach offers several advantages:

  • Concurrency: The operations will be executed concurrently without waiting for the first to complete.
  • Rejection Handling: Any rejections will be handled properly, and the resulting promise will reject with an appropriate error.
  • Simplicity: The syntax is concise and readable.

TL;DR

In summary, to perform concurrent asynchronous operations with proper rejection handling, use Promise.all:

<pre>
const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]);
</pre>

Dernier tutoriel Plus>

Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.

Copyright© 2022 湘ICP备2022001581号-3