Jul 7, 2016

JavaScript: Parallel and Serial AJAX Requests




Sometimes you need to do a lot of AJAX requests to collect data, from the same server, but what if the server doesn't accept or even can't handle all those requests at same time, due to bandwidth or even security limitations? whatever is the reason, the solution could be sent each request just when the previous one has been successfully done, and here you can see how!

For this example we will use the '$.ajax' method from the jQuery library, that provides an easy way to do an AJAX GET request. So let's assume that we have a list of objects which have only the code attribute filled, and for every object we need to get its respective name from the server, using an AJAX GET request, then we have the following:

<html>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script type="text/javascript">
 
 var objects = [{code:1,name:null},{code:2,name:null},{code:3,name:null}];
 
 for(var object in objects)
 {
  
  $.ajax({
   url: 'http://l3oc.com/get/'+objects[object].code,
   method: 'GET'
   }).then(function(data) {
    objects[object].name=data;
  });
  
 }
 
</script>
</html>

As we can see, the code will dispatch 3 AJAX requests in parallel:


But to dispatch them in sequence, we'll need use threads (as seen here), then the code could be something like this:

<html>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script type="text/javascript">
 
 var objects = [{code:1,name:null},{code:2,name:null},{code:3,name:null}];
 var isDoingRequest = false;

 for(var object in objects)
  setTimeout(thread, 1,object);
 
 function thread(object)
 {
  if(!isDoingRequest)
  {
   isDoingRequest = true;
   
   $.ajax({
    url: 'http://l3oc.com/get/'+objects[object].code,
    method: 'GET'
    }).then(function(data) {
    objects[object].name=data;
    isDoingRequest=false;
   });
   
  }
  else
  setTimeout(thread, 1,object);
 };
 
</script>
</html> 

As we can see above, the variable 'isDoingRequest' acts like a flag, that tell us if there is or not a request going on, if yes, the thread waits until the other thread request is successfully done, then the flag will change unblocking the thread that is waiting and so on. Now we can see the resulting change that really matters:


That's all !

0 comentários :

Post a Comment