Hi, In the fast-paced world of JavaScript development, mastering asynchronous operations is key to building robust and efficient applications. However, there’s a common misconception among developers about using async functions as callbacks of forEach method. In this blog post, we’ll talk about this myth and explore the power of ‘for…of’ loops for handling asynchronous tasks effectively.
While forEach is a handy array method and earlier I also used to use the async function inside the array “forEach” loop as the callback function when I didn’t know its limitations. Then I got to know about this in my code testing report given by SonarQube(a tool for testing the code). You can better understand the scenario with the below example.
const mediaIds = [1,2,3,4,5]; const uploadImagesToServer=async()=>{ mediaIds.forEach(async(mId,index)=>{ await uploadMedia(mId); console.log("Index :",index) }) } uploadImagesToServer(); //This is the case which I am talking about
It lacks the control and predictability needed for managing async tasks. And we can not handle errors gracefully because ‘uploadMedia()’ function above will not get executed sequentially according to the elements in mediaIds array.
Why to use for…of Loop :
1.Controlled Execution: Unlike forEach, for…of loops execute iterations sequentially, ensuring each async operation completes before moving to the next.
2.Error Handling Made Easy: With for…of loops, error handling becomes straightforward. Each iteration waits for the previous one to finish, making error detection and resolution a breeze.
const mediaIds = [1,2,3,4,5]; const uploadImagesToServer=async()=>{ for(const mId of mediaIds){ await uploadMedia(mId); } } uploadImagesToServer() //This is the other and eficient way for these kind of use cases.
Now you might be thinking🤔 what about the index which we were getting in ‘forEach’ as the second argument😁?
Don’t worry we can also have our index in this way by using ‘for…of’. Do you know about the .entries() method? If not please google it. So we will use this method to fulfill our requirement of index.
const mediaIds = [1,2,3,4,5]; const uploadImagesToServer=async()=>{ for(const [index,mId]of mediaIds.entries()){ await uploadMedia(mId); console.log("Index :",index) } } uploadImagesToServer() //If you are not aware about .entries() iterator. Please google it.
Conclusion:
In conclusion, “for…of” loops are a game-changer for handling asynchronous operations in JavaScript. They offer control, clarity, and simplicity — essential ingredients for modern development.
3 Comments
1
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.