Async forEach, Map and Filter in JavaScript

By Kumar Manish Chaubey

Manish Chaubey
1 min readApr 4, 2020

In 2017 when ES8 released with best enhancement but there is a breaking changes of async/await where We can wait for the execution till the promise returns. But it fails in prototype functions of array when we use map, foreach etc.

What will happen in code bellow ?

So as we know the behavior of promise iteration should wait for someAsyncOperation till execution one completes for one process. But it will not wait for async operation.

Process execute before you catch

What to do ?

Now let’s think in traditional way and create your own custom iterator which can help to accomplish our requirement.

Create a function asyncForEach to iterate over every item of array where line_items is an array and asyncIterator is an iterator to process each value of array asynchronously.

Note: Please keep in mind that asyncIterator must return a promise.

asyncForEach

And here we go….

Now this call will wait for execution of someAsyncOperation to complete for each item and execution will work in Asynchronous way in JavaScript.

Please note that callback function must return Promise.

Async For Each Operation

Now the task is for you to create async map and filter Let’s do that….

Thank You for Reading suggestion are valuable to improve :)

Manish Chaubey

--

--

Manish Chaubey

Founder KCSS Infotech, Crafting my journey of learning through writing :)