Simple AJAX And Nested Async AJAX Request Handling In JS

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,
  1. for(var i=1;i<10;i++){  
  2. var reqUrl='https://jsonplaceholder.typicode.com/todos/'+i;  
  3. fetch(reqUrl)  
  4.   .then(response => response.json())  
  5.   .then(json => console.log(json,i))  
  6. }  
Output of the above code can be seen as below. In the execution, you may notice the result at the end of response 10 is printed in the console, which is index value. Here for loop is syncronous and fetch request is asyncronous.
 
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.
  1. The index  value is not synced with the response, meaning  value of i and id should be same
  2. As order of execution is not in order, how will we know twhether it is completed or not?
Simple AJAX And Nested Async AJAX Request Handling In JS
 
Example 2
 
Async request inside for loop but inside the function scope:
  1. // wrapped async fetch request inside function  
  2. function makeRequest(i){  
  3. var reqUrl='https://jsonplaceholder.typicode.com/todos/'+i;  
  4. fetch(reqUrl)  
  5.   .then(response => response.json())  
  6.   .then(json => console.log(json,i))  
  7. }  
  8.   
  9. // Call async request inside for loop.  
  10. for(var i=1;i<10;i++){  
  11.    makeRequest(i);  
  12. }  
Here we have wrapped async fetch request inside one javascript function which will solve our first issue in which index value and result id is matching which is clearly seen in the screenshot.

Simple AJAX And Nested Async AJAX Request Handling In JS
 
Example 3
 
Async request is inside for loop, but inside the function scope verifying the total request and successfully executed request.
 
Using this method you can solve the second problem, to detect or know whether all request are completed or not.  You can also extend logic if any error occurs while requesting.
  1. var tatalRequestCount=10;  
  2. var tatalRequestCount=0;  
  3.   
  4. //  
  5. function makeRequest(i){  
  6.    var reqUrl='https://jsonplaceholder.typicode.com/todos/'+i;  
  7.    fetch(reqUrl)  
  8.   .then(response => response.json())  
  9.   .then(json => {  
  10.       console.log(json,i);  
  11.       //Ensure successful request execution  
  12.       executedRequest++;  
  13.   
  14. if(tatalRequestCount===executedRequest){  
  15.    //TODO  when you need to perform action once all request are executed update list or insert something  
  16.    console.log("All Request are executed");  
  17.    }  
  18.  });  
  19. }  
  20.   
  21. // Start async call inside loops  
  22. for(var i=1;i<=tatalRequestCount;i++){  
  23.    //Make sure before making request set counter to 0 if you are running this multiple times  
  24.    executedRequest=0;  
  25.    makeRequest(i);  
  26. }  

Conclusion

 
In this article we got a basic idea about some known issue with async call inside loops and to solve problems.


Similar Articles