Node.js — Run Async Functions/Promises in Parallel

With the release of Node.js v8, async functions became an integral component. Async functions provide a simpler API around promises by removing (most) of the callback-y code.

The combination of async/await and promises is powerful, but you have to be careful not going too sequential.

This tutorial shows you two ways of running async functions or promises in parallel.

Node.js Series Overview

Code Samples

Find the executable code examples for this tutorial in the nodejs-tutorials repository on GitHub. You can run both files in the linked directory:

node index.js

# or

node with-errors.js  

Have fun!

Preparations

The examples in this tutorial simulate asynchronous processing by waiting for a period of milliseconds. This waiting time imitates the functionality you may run in your application, e.g., fetching data from an API, loading data from the file system, or running database queries.

The function simulating asynchronous requests has the signature asyncProcessing(ms). It accepts an integer as a parameter which represents the waiting time in milliseconds:

async function asyncProcessing (ms) {  
  await new Promise(resolve => setTimeout(ms, resolve))

  console.log(`waited: ${ms}ms`)

  return ms
}

The upcoming examples use the asyncProcessing() function.

Approach 1: Run Promises in Parallel Using “for…of”

Using a loop to run async functions in parallel seems odd. Actually, the for…of loop is required to pick the results from each promise.

The gimmick to run all promises in parallel is using the default behavior of promises being eager. That means, as soon as you create a promise it starts processing in the background. You don’t need to start a promise. It fires right out of the gates.

The following code block outlines how to create a list of promises with the help of .map(). The .map() function returns an array of promises that you then need to await:

async function forLoopInParallel () {  
  const result = []
  const timeouts = [10, 600, 200, 775, 125, 990]
  const promises = timeouts.map(timeout => asyncProcessing(timeout))

  for (const timeoutPromise of promises) {
    result.push(await timeoutPromise)
  }

  return result
}

timeouts.map() returns a list of promises that already started their processing. What’s left for you is iterating through the list of promises and receive the results.

Approach 2: Run Promises in Parallel Using “Promise.all()”

The global Promise object in JavaScript has a convenience method Promise.all() which returns a promise that resolves as soon as all promises in the iterable resolved.

The following example creates a list of promises with the help of .map(). You can then wait for these promises to resolve using Promise.all():

async function awaitAll () {  
  const timeouts = [10, 600, 200, 775, 125, 990]
  const promises = timeouts.map(timeout => asyncProcessing(timeout))

  const result = await Promise.all(promises)

  return result
}

This approach reduces the amount of code because Promise.all() encapsulates everything you need. Sweet!

Error Handling

Firing off a list of promises in parallel may cause errors. For example, you may run into an API rate limiting or exceed your server’s resources.

Both code examples show optimistic implementations. There’s no try/catch block to catch any error and handle it. Please make sure that you’re not blowing up your app by skipping the error handling.

The nature of promises being eager may result in an unexpected control flow. As soon as one of the promises rejects, all other promises won’t stop. They still proceed with their processing in the background. But your application code won’t wait for them to finish.

Have a look at the linked examples to get a grasp on the control flow in error situations. We recommend you to run the with-errors.js sample file to feel what’s happening.


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.