DEV Community

Cover image for Using for await...of to Iterate Over Synchronous and Asynchronous Arrays in JavaScript
Thiago Marinho
Thiago Marinho

Posted on

Using for await...of to Iterate Over Synchronous and Asynchronous Arrays in JavaScript

👋🏻 Asynchronous programming is essential in JavaScript when dealing with time-consuming operations like fetching data from APIs, reading files, or handling delays. ES6 introduced Promises to handle asynchronous tasks more elegantly.

Subsequently, ES2018 introduced the for await...of loop, which further simplified handling asynchronous data when working with async iterable like Promises or Generators.

In this blog post, we will explore how to use for await...of to iterate over both synchronous and asynchronous arrays.

Example: Asynchronous Array

Consider an example where we have an array of delays, and we want to execute asynchronous tasks for each delay in the array.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const createDelays = [1000, 2000, 500, 3000, 5000, 10000, 100].map(ms => delay(ms));

const asyncIterable = createDelays;

(async () => {
  for await (const delayTime of asyncIterable) {
    console.log(`Waited for ${delayTime} milliseconds.`);
  }
  console.log("All delays processed.");
})();
Enter fullscreen mode Exit fullscreen mode

In this example, we define the delay function that returns a Promise, simulating an asynchronous delay. We then create an asynchronous array createDelays, containing Promises that resolve after different delays. Using for await...of, we can iterate over the asyncIterable and await each Promise's resolution before moving to the next item. This ensures that each delay is processed sequentially.

Example: Synchronous Array

Now let's consider an example where we have an array of delays and want to execute synchronous tasks for each delay in the array.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function processDelays(delays) {
  for await (const delayTime of delays) {
    await delay(delayTime);
    console.log(`Waited for ${delayTime} milliseconds.`);
  }
  console.log("All delays processed.");
}

const delaysArray = [1000, 2000, 500, 3000, 5000, 10000, 100];
processDelays(delaysArray);

Enter fullscreen mode Exit fullscreen mode

In this example, we define the delay function similarly to the previous example. The function processDelays takes an array of delays and iterates over them using for await...of. Although the array is synchronous, the loop becomes asynchronous due to the await inside it. This allows us to handle each delay asynchronously, one after the other.

Example: Mixed Array with Asynchronous Operations

function fetchData(data) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(`Data: ${data}`);
    }, Math.random() * 5000); // Simulate a random delay up to 5000 ms (5 seconds).
  });
}

async function processArrayWithAsyncOperations(dataArray) {
  for (const data of dataArray) {
    const result = await fetchData(data);
    console.log(result);
  }
  console.log("All operations processed.");
}

const dataArray = [1, 2, 3, 4, 5];
processArrayWithAsyncOperations(dataArray);

Enter fullscreen mode Exit fullscreen mode

In this example, we define the fetchData function, which simulates fetching data asynchronously with a random delay. The function processArrayWithAsyncOperations iterates over the dataArray using for await...of. Even though the data fetching itself is asynchronous, the loop processes each item sequentially due to the await statement.

Conclusion

We covered the usage of for await...of to iterate over both synchronous and asynchronous arrays. This loop allows us to handle asynchronous data elegantly, ensuring sequential processing of each item. Whether you're working with pure asynchronous data, pure synchronous data, or a mix of both, for await...of provides a powerful tool for handling asynchronous tasks with ease in modern JavaScript.

You can see the code in action the replit.com

👨🏻‍💻 🚀

Top comments (1)

Collapse
 
tgmarinhodev profile image
Thiago Marinho