如何让jQuery等到一个循环完成

时间:2016-06-29 06:24:10

标签: jquery ajax jsp

for (var i = 0; i < responseJson.length; i++) {
  if (responseJson[i].Framework == "FPS") {
    ExecuteFps(responseJson[i], payload);
  } else if (responseJson[i].Framework == "OATS") {
      var data = responseJson[i];
      // Here i need one iteration to complete all its task and it should allow another one. I mean I want it to run serially.
      $.when(a(responseJson[i], responseJson[i].Path)).done(function() {
        removeItemResponse(data)});
      }

function a(data, folderpath) {
  var def = $.Deferred();

  var template = $("#template").val();
  var ref = JSON.stringify(ref);
  var path = document.getElementById('automationPathText').value;
  var projectId = $("#projectId").val();
  var serverpath = $("#serverPathText").val();
  var parallelProcess = "No";
  //alert("aaaaaaaaaaaaaaa");

  $.ajax({
    url: "Target",
    data: {
      template: template,
      data: JSON.stringify(data)
    },
    type: "POST",
    success: function(responseJson) { 
      //document.IOProcessStream.learnApplication("D:\\AutomationTesting\\","IE","No","D:\\AutomationTesting\\ServerConfiguration\\","No");
      //document.IOProcessStream.generateScript("D:\\AutomationTesting\\","D:\\AutomationTesting\\ServerConfiguration\\");
      if (responseJson.Status === "NOREFERENCE" || responseJson.Status === "SUCCESS") {
          document.IOProcessStream.gateway(path, projectId, folderpath, serverpath, "IE");
          //alert("After document....");
          document.IOProcessStream.executeApplication(folderpath, path, "No", "IE", serverpath, "No", data);
          console.log("IN a");
          def.resolve();    
      }
    }
  });

  return def.promise();
}

2 个答案:

答案 0 :(得分:0)

首先,我们会深入挖掘您的代码。

  1. 您不应在循环内创建函数,不建议这样做。
  2. 该函数运行asynchonosly,因为它正在进行Ajax调用。这就是为什么循环从不等待它完成并继续执行。
  3. 要解决此问题,您需要重新安排代码。这些事情已被多次解释,所以为了保持简单,这是我对你的建议。

      

    function a()移到循环之外,并为其指定有意义的名称。第二件事是将代码内部循环包含在closure中,以在每次迭代中捕获i的值。

    这就是它的样子。

    for (var i = 0; i < responseJson.length; i++) {
        if (responseJson[i].Framework == "FPS") {
            ExecuteFps(responseJson[i], payload);
        } else if (responseJson[i].Framework == "OATS") {     
            (function(i){
                // it will catch i in each iteration!
                var data = responseJson[i];
                $.when(someMeaningFullName(data, data.Path)).done(function() {
                    removeItemResponse(data)
                });
            })(i);
        }
    }   // loop ends here!
    
    // this is your function a() outside the loop!
    function someMeaningFulName(data, folderpath) {
        // same code...
    }
    

答案 1 :(得分:0)

您可以使用$.when()Function.prototype.apply()$.map()替换for循环; $.Deferred()函数a也不是必需的,你可以return $.ajax()返回一个jQuery promise对象。

请注意ExecuteFpsremoveItemResponse函数的返回值是什么?

$.when.apply($, $.map(responseJson, function(response, i) {
  if (response.Framework == "FPS") {
         return ExecuteFps(response, payload)
  } else if (response.Framework == "OATS") {
           return a(response, response.Path))
             .done(function() {
               removeItemResponse(response)
             })
}))

function a(data, folderpath) {
  return $.ajax(/* options */)
}