系列的jquery调用

时间:2016-12-07 23:03:08

标签: javascript jquery ajax deferred

我目前有一系列需要按特定顺序执行的ajax调用。它们中没有一个是完全可行的。

但实质上所有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");
                            });
                        });
                    });
                });
            });
        });
    }

查看示例hereStackoverflow answer: ordering ajax calls并尝试使用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"
    });
}

1 个答案:

答案 0 :(得分:2)

只需使用then

(确保传递给每个函数然后返回一个promise,否则它将被视为一个立即解决的promise)。

您的代码,重构:

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>