Introduction
In this article, we will learn about handling the nested async request and async ajax request inside for loop.
Description
If you have worked with Web API and consuming Web API or any REST API in Javascript or Angular or React then you definitely faced an issue with Asynchronous request.
Consider a scenario in which for a specific city you are requesting Google maps API to find a hospital or ATM and with a pincode which may return multiple results and now you also want to get an area or address based on that pincode value.
So, for such a situation, you might have faced an inconsistency in result due to the async request.
Let's understand this situation with an example to get a better idea about what we are talking about.
For this demo, I will be using native fetch API which is responsible for making ajax request.
Example 1
Async request inside for loop without function,
- for(var i=1;i<10;i++){
- var reqUrl='https://jsonplaceholder.typicode.com/todos/'+i;
- fetch(reqUrl)
- .then(response => response.json())
- .then(json => console.log(json,i))
- }
You might expected the value of index along with return result.
One more point you need to notice is that we have made async requested in sequence but in the result you can see id value which is not in order.
So here we have two issues.
- The index value is not synced with the response, meaning value of i and id should be same
- As order of execution is not in order, how will we know twhether it is completed or not?

Example 2
Async request inside for loop but inside the function scope:


Join the conversation! Your thoughts help the community grow.