JavaScript is known for its non-blocking calls using callbacks, promises, and async/await. Occasionally the need will arise to process a collection of non-blocking calls either sequentially or in parallel.

Set Up

Let’s say we need to make a collection of API calls. Our mock api will be a function that will return a promise that will resolve after 1 second.

const apiEndpoints = ["first", "second", "third"];

const apiCall = endpoint => new Promise(resolve => setTimeout(resolve, 1000));

Parallel Processing

In this case, the execution order for the API calls are not important, we just need to know when they have all completed.

const parallel = Promise.all(apiEndpoints.map(apiCall));

#javascript #parallel-processing #async-functions #sequential-processing #promises #programming

Sequential and Parallel Asynchronous Functions
1.45 GEEK