daredadevil
daredadevil

Reputation: 327

Series of jquery calls

I currently have a series of ajax calls that need to be performed in a certain order. None of them are exactly doable in parallel.

But in essence all performSeriesofCalls does is make ajax calls in the exact order of Call1 -> Call2 -> Call3 -> Call4 -> Call5.

    performSeriesofCalls: function () {
       doThisFirst(function () {
            Service.call1(arg1,arg2).done(function (modelData) {

                updateModel(modelData);
                var saveId = modelData.Id1;
                var discardId = modelData.id2;

                Service.call2(saveId, arg4).done(function () {

                    Service.call3(discardId).done(function () {

                        Service.call4(saveId).done(function () {

                            Service.call5(saveId).done(function (savedModel) {

                                updateModel(savedModel);
                                updateMessage("Performed");
                            });
                        });
                    });
                });
            });
        });
    }

Looked at examples here and Stackoverflow answer: ordering ajax calls and tried refactoring into the following using jQuery.when(), but I want to know if can do better.

 performSeriesofCalls: function () {
            doThisFirst(function () {
                Service.call1(arg1,arg2).done(function (modelData) {

                    updateModel(modelData);
                    var saveId = modelData.Id1;
                    var discardId = modelData.id2;;

                    jQuery.when(
                        Service.call2(saveId, arg4)

                    ).done(function () {
                        jQuery.when(
                            Service.call3(discardId),
                            Service.call4(saveId)
                        ).done(function () {
                            Service.call5(saveId).done(function (savedModel) {
                                updateModel(savedModel);
                                updateMessage("Performed");
                            });
                        });
                    });
                });
            });
        } 

note: Service.js contains the actual ajax requests for the sake of modularity.

sample calls in Service.js

/**
 * Update Status 
 * @returns {jqXHR} From the jQuery.ajax() call
 */
call2: function (quoteId, action) {
    return jQuery.ajax({
        method: "POST",
        url: serviceURL + "/endpoint/" + quoteId + "/action",
        data: JSON.stringify(action),
        contentType: "application/json"
    });
}

Upvotes: 0

Views: 266

Answers (1)

abl
abl

Reputation: 5958

Just use then.

(make sure that every function passed to then returns a promise, otherwise it will be treated as an immediately resolved promise).

Your code, refactored:

doThisFirst(function () {

    return Service.call1(arg1,arg2);

}).then(function (modelData) {

    updateModel(modelData);
    var saveId = modelData.Id1;
    var discardId = modelData.id2;;
    return Service.call2(saveId, arg4)

}).then(function () {

    return jQuery.when(
        Service.call3(discardId),
        Service.call4(saveId)
    );

}).then(function () {

    return Service.call5(saveId).done(function (savedModel) {
        updateModel(savedModel);
        updateMessage("Performed");
    });

}).then(function(){

  // whatever

});

The following snippet is a visual example of how then works:

doProcess("A", 3).then(function(){
  return doProcess("B", 3);
}).then(function(){
  return doProcess("C", 2);
}).then(function(){
  return $.when(
    doProcess("D.1 (in parallel)", 5),
    doProcess("D.2 (in parallel)", 3)
  );
}).then(function(){
  return doProcess("E", 2);
}).then(function(){
  $("#processlist").append("<h2>All done!</h2>");
});


function doProcess(name, time) {

  var $domElem = $("<div/>", {
    "class": "processelem"
  });
  var $secondsSpan = $("<span/>");
  $domElem.append("Process " + name + ", finishing in ");
  $domElem.append($secondsSpan);
  $("#processlist").append($domElem);
  
  var timeLeft = time;
  $secondsSpan.text(timeLeft);
  
  var def = $.Deferred();
  var decrement = function(){
    timeLeft--;
    if(timeLeft >= 0){
      $secondsSpan.text(timeLeft);
      setTimeout(decrement, 1000);
    } else {
      $domElem.text("Process " + name + " (finished)");
      $domElem.addClass("finished");
      def.resolve();
    }
  }
     
  decrement();
     
  return def.promise();

}
.finished {
  color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="processlist"></div>

Upvotes: 2

Related Questions