How to optimize await in loops - Nodejs way

How to optimize await in loops - Nodejs way

Using await inside the loop is not a best practice and overall it will affect the performance. This is because it'll pause the true purpose of Node.js asynchronous.

Please note that I'll update this article based on my learning esp like when the API call failed or how to do the error handling properly. I am dumping this here for learning myself as well. So, if you've any improvements to see here, feel free to comment or reach out at makeinfo14[@]gmail.com

In the below sample snippet, I'm assuming that getDataFromApi() is the callable function to get data from the API/service.


function test () { 
    const urlArrs = ["test","test2","test3"];
    let resultArr = [];

  const resultArr = urlArrs.map((url)=> {
           try {
               return getDataFromApi(url);
           }
           catch (error) {
                  return ("Error");
           }
   } );

   //console.log(await Promise.all(resultArr));
   return await Promise.all(resultArr)
}

As you can see the magic happens when you put await Promise.all around that array function. Please check this StackOverflow page to see the difference between Promise.all and multiple awaits

References

https://zellwk.com/blog/async-await-in-loops/

https://eslint.org/docs/rules/no-await-in-loop