Paolo Rossi
Paolo Rossi

Reputation: 2510

Jquery ajax perform sequentially response

In my plugin I'd like to sequentially ajax call and response, because the next response depends to the previous. Unfortunately, the responses do not match the call order (I don't want to use async: false) and so I should handle this thing.

var array = ['a', 'b', 'c', ...]; <- dynamic values
var params = ['foo', 'bar', 'doe', ...]; <- dynamic values
var postData = {};

$.each ( array, function ( idx, val ) {
    postData.value = val;
    var param = params[idx];
    ajaxRequest( param, callback );
});

var ajaxRequest = function ( param, callback ) {
    $.ajax ({
        url: url,
        data: postData,
        type: "POST"
    }).done ( function ( data ) {
        //a returned data in 5 sec
        //b returned data in 3 sec
        //c returned data in 1 sec
    });
}

I have read some things about ajax promise and deferred, but I do not know IF and HOW it can be the correct solution for my scenario
How could I do this?
Thank you

Upvotes: 0

Views: 60

Answers (1)

ADyson
ADyson

Reputation: 61984

You can use the "done" function of the ajax request to ensure the requests are chained together sequentially, since this callback doesn't execute until the request has successfully completed. Something like this (un-tested):

var arr = ['a', 'b', 'c', ...];
var params = ['foo', 'bar', 'doe', ...];
var arrIndex = 0;

function ajaxRequest() {
   console.log("Request " + arrIndex + " starting");
    var postData = { value: arr[arrIndex] };
    var param = params[arrIndex];

    $.ajax ({
        url: url,
        data: postData,
        type: "POST"
    }).done ( function ( data ) {
      console.log("Request " + arrIndex + " completed");
      arrIndex++;
      if (arrIndex < arr.length) {
        ajaxRequest();
      }
      else {
          console.log("All requests completed");
      }
    });
}

I'm not sure what the purpose of "param" is, because you don't seem to use it in the example, but I've left it in, in case you need it in reality. "callback" seemed to do nothing at all, so I've ignored that.

You probably also want to consider what to do if any particular request fails - I assume you can't continue, so maybe you just need to log the error, but I'll leave that to you.

Upvotes: 1

Related Questions