jquery 系列电话

Series of jquery calls

我目前有一系列 ajax 调用需要按特定顺序执行。 None 其中完全可以并行执行。

但本质上 performSeriesofCalls 所做的只是按照 Call1 -> Call2 -> Call3 -> Call4 -> Call5.

的确切顺序进行 ajax 调用
    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");
                            });
                        });
                    });
                });
            });
        });
    }

看了例子here and Whosebug answer: ordering ajax calls and tried refactoring into the following using jQuery.when(),但我想知道是否可以做得更好。

 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");
                            });
                        });
                    });
                });
            });
        } 

注意:Service.js 包含实际的 ajax 请求以实现模块化。

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"
    });
}

只需使用then

(确保传递给 then returns 的每个函数都是一个承诺,否则它将被视为立即解决的承诺)。

你的代码,重构:

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

});

以下代码段是 then 工作原理的直观示例:

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>