KingJames
KingJames

Reputation: 556

http request in while loop in JavaScript

I am trying to send a xmlHttpRequest in a while loop and want to do something with the response in the same while loop. Since the requests are asynchronous, how can I achieve it? I need to execute everything serially

while(i < n){
 response = self.sendHttpRequest(params);
 //do something with the response
}

Any help would be appreciated. Even If I use a callback, how can I get back to same while loop after executing the callback?

Upvotes: 2

Views: 3173

Answers (2)

balajisoundar
balajisoundar

Reputation: 571

Are you using any ajax library or plain js. If you are not using any library ,you can pass third argument to open method false.like below

var xmlHttp=new xmlHttpRequest(); xmlHttp.open({YOUR_METHOD},{YOUR_PATH},false);

Passing false to open method makes synchronous call .so you can handle the return in same loop.

Upvotes: 1

Eyal
Eyal

Reputation: 532

There are two ways I can think of:
1. Add a polling loop after the get call that waits until the response.readyState is set and then process the response:

while(i < n){
 response = self.sendHttpRequest(params);
 while( response.readyState != 4 ){
     // polling wait
 }
 //do something with the response
}

This option is not really recommended since it stops the flow of the code and you can get stop in the loop if the readyState never changes (not likely, but possible with errors).


2. You can encapsulate the request in a function that will be called recursively when the last response handling finishes:

var i = 0;
function handle( response ){
    //handle response
    i++;
    if( i < n ) sendRequest();
}

function sendRequest(){
    // Your request setup code
    response.onreadystatechange = handle;
    response = self.sendHttpRequest(params);
}


The second method is preferred in my opinion, as it maintains the asynchronicity of the html request call, and doesn't stop the flow of the code, however it does "break" the loop structure. The first method keeps the loop structure, but is not very good coding practice.

Upvotes: 0

Related Questions