Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to use async/await with forEach loop in JavaScript ?

How to use async/await with forEach loop in JavaScript ?

Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code.

Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.

Using async/await in forEach loop

 

Approach: 

  • Create an array eg. myArray that contains some values.
  • Create an async main function that calls another async function that says doSomethingAsync
  • Now create an async function in which we use setTimeout to print all the items of the array.
  • This function returns a promise that resolves when the delay is complete.

Javascript




<script>
    const myArray = [1, 2, 3, 4, 5];
  
    // A function that returns a promise 
    // that resolves after a random delay
    async function doSomethingAsync(item) {
        return new Promise(resolve => {
            setTimeout(() => {
                console.log(item);
                resolve();
            }, Math.random() * 1000);
        });
    }
  
    async function main() {
  
        // Wait for all promises returned by 
        //doSomethingAsync to resolve.
        await Promise.all(
          
            // Use map to create an array of promises, 
            // with one promise for each item in myArray.
            myArray.map(async item => {
                  
                // Wait for the promise returned by 
                //doSomethingAsync to resolve.
                await doSomethingAsync(item);
            })
        );
    }
  
    // Call main to start the program.
    main();
</script>


Working : 

  • The main function is marked as async, which means it returns a promise.
  • We use Promise.all to wait for all the promises returned by doSomethingAsync to complete before moving on to the next line of code.
  • Inside the Promise.all calls, we use a map to create an array of promises that each call doSomethingAsync for a single item in the array.
  • We use the await keyword to wait for each promise to complete before moving on to the next item in the array.

Output : 

output GIF of async/await in forEach loop

Another Example : 

Javascript




<script>
    const myArray = ["neveropen", "for", "neveropen"];
  
    // A function that returns a promise 
    //that resolves after a random delay
    async function doSomethingAsync(item) {
        return new Promise(resolve => {
            setTimeout(() => {
                console.log(item);
                resolve();
            }, Math.random() * 1000);
        });
    }
  
    async function main() {
  
        // Wait for all promises returned 
        // by doSomethingAsync to resolve
        await Promise.all(
  
            // Use map to create an array of promises, 
            // with one promise for each item in myArray
            myArray.map(async item => {
                  
                // Wait for the promise returned by
                // doSomethingAsync to resolve
                await doSomethingAsync(item);
            })
        );
    }
  
    // Call main to start the program.
    main(); 
</script>


Output:

async/await in forEach loop

Explanation: Due to the delay in printing elements, another element ” for ” is printed before the first element “neveropen” in myArray to save time. It depicts that the asynchronous function run simultaneously.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments