Categories
JavaScript Answers

How to iterate asynchronously over JavaScript arrays?

Spread the love

Sometimes, we want to iterate asynchronously over JavaScript arrays.

In this article, we’ll look at how to iterate asynchronously over JavaScript arrays.

How to iterate asynchronously over JavaScript arrays?

To iterate asynchronously over JavaScript arrays, we can use the for-of loop and run async code with promises inside the loop body.

For instance, we write:

(async () => {
  let value = 0
  const arr = [0, 1, 2, 3, 4, 5]
  for (const a of arr) {
    value += await (Promise.resolve(a))
    console.log(value)
  }
})()

We use the for-of loop to loop through the arr array.

Inside the loop body, we call Promise.resolve with ato return a promise that resolves toa`.

And we use await to wait for the promise to resolve and we return the resolved value from the promise.

We then add the resolved value to value and log it.

Therefore, we see:

0
1
3
6
10
15

logged in the console.

Conclusion

To iterate asynchronously over JavaScript arrays, we can use the for-of loop and run async code with promises inside the loop body.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *