How to Use Async functions with array. forEach in Javascript – Tamas Sallai A stable network environment is required

How do I traverse elements asynchronously

In the first article, we showed how async/await helps with asynchronous events, but not with collections asynchronously. In this article, we’ll look at this forEach feature, which can be useful when you need to run a piece of code forEach element in a collection.

1. forEach

This forEach function is similar to map, but instead of converting the value and using the result, it runs the function forEach element and discards the result. In fact, the important part is the side effects of calling the function.

For example, to print each element synchronously to the console:

const arr = [1.2.3];



arr.forEach((i) = > {

 console.log(i);

});



/ / 1

/ / 2

/ / 3



console.log("Finished sync");

// Finished sync

Copy the code

Since the result is not important, we can use asynchronous functions as iterators:

const arr = [1.2.3];



arr.forEach(async (i) => {

 // each element takes a different amount of time to complete

 await sleep(10 - i);

 console.log(i);

});



console.log("Finished async");

// Finished async



/ / 3

/ / 2

/ / 1

Copy the code
Async forEach image

2. Control your time

2.1 Wait Completion

Not surprisingly, however, the function is called asynchronously and the program executes outside the scope of the call. This is an important difference from the synchronous version, because when the next line is executed, the synchronous forEach is done, while the asynchronous version is not. This is why the completed asynchrony log appears before the element.

To wait for all function calls to complete before proceeding, use a map with promise.all and discard the result:

const arr = [1.2.3];



await Promise.all(arr.map(async (i) => {

 await sleep(10 - i);

 console.log(i);

}));



/ / 3

/ / 2

/ / 1



console.log("Finished async");

// Finished async

Copy the code
Async map image

After making this change, “Completed asynchronous operation” is ranked last.

2.2 Sequential Processing

Note, however, that the iterating functions are called in parallel. To faithfully follow synchronous forEach, use reduce with await Memo first:

const arr = [1.2.3];



await arr.reduce(async (memo, i) => {

 await memo;

 await sleep(10 - i);

 console.log(i);

}, undefined);



/ / 1

/ / 2

/ / 3



console.log("Finished async");

// Finished async

Copy the code
Async reduce image

In this way, the elements are processed in sequence, and program execution will wait for the entire array to complete before continuing.

Conclusion 3.

Asynchronous forEach is easy to use, but whether you should use forEach, Map, or Reduce depends on timing requirements. If you only want to run these functions at any time, use forEach. To ensure that the operation is complete before continuing, use map. Finally, if you need to run them one by one, use Reduce.

Recommended reading:

  • How to use anti – shake throttling gracefully in Vue