"Si un trabajador quiere hacer bien su trabajo, primero debe afilar sus herramientas." - Confucio, "Las Analectas de Confucio. Lu Linggong"
Página delantera > Programación > 在JavaScript中如何并发运行异步操作并正确处理错误?

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

Publicado el 2025-05-03
Navegar:791

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>

Último tutorial Más>

Descargo de responsabilidad: Todos los recursos proporcionados provienen en parte de Internet. Si existe alguna infracción de sus derechos de autor u otros derechos e intereses, explique los motivos detallados y proporcione pruebas de los derechos de autor o derechos e intereses y luego envíelos al correo electrónico: [email protected]. Lo manejaremos por usted lo antes posible.

Copyright© 2022 湘ICP备2022001581号-3