【问题标题】:How to check when the functions initiated by the loop have completed?如何检查循环启动的功能何时完成?
【发布时间】:2015-04-24 18:55:47
【问题描述】:

我正在运行 match() 以循环遍历数组或停止 ID。对于每个停止 ID,我将调用一个函数,该函数循环遍历另一个路由 ID 数组并通过 AJAX 调用的响应来查找匹配项。

如果它在数组中的 routeID 和 RouteID 之间找到匹配项,则在每个循环中将结果添加到另一个数组中。

我的问题是我找不到方法来确定 match() 循环调用的函数何时完成。

我需要这样做的原因是,我需要确保jpFromStops 数组是完整的并且可以被另一个函数处理。

最好的方法是什么?

   function match() {
        // Array length is 5
        for(i=0; i < fromStopsAr.length; i++) {
            getFromRoutesStopId(fromStopsAr[i]);
        }
        console.log("Match Array Output: " + jpFromStops.toString());
    }

function getFromRoutesStopId(id) {
   jpFromStops=[];
   tempAr = [];

  jQuery.ajax({
    type: "GET",
    url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
    dataType: "jsonp",
    cache: false,
    crossDomain: true,
    processData: true,

    success: function (data) {
    $.each( matchRoutes, function(index, value) {
      $.each(data.response, function(key, data) {
          if(data.route_short_name.toString() == value) {
             jpFromStops[jpFromStops.length] = id + ":" + value;      
          }
      });   
     }); 
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("There is a problem");
    }
  });
}

控制台日志输出:

Match Array Output: 
jp-main.js (line 177)
2
115
jp-main.js (line 199)
2
113
jp-main.js (line 199)
2
087

【问题讨论】:

  • 添加一个在成功或错误时递增的计数器,当它匹配fromStopsAr.length时,你就完成了。
  • @brso05 当我多次调用“getFromRoutesStopId(id)”时,我该怎么做。
  • @Ted 该计数器会在 Ajax 调用的成功块结束时结束吗?
  • @Yonkee——见 jcubic 的回答。更好/
  • @brso05 我认为 JSONP 和跨域调用不支持 async:false。

标签: javascript jquery ajax loops


【解决方案1】:

你可以使用计数器……有点像:

var count = 0;
function getFromRoutesStopId(id) {
   jpFromStops=[];
   tempAr = [];

  jQuery.ajax({
    type: "GET",
    url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
    dataType: "jsonp",
    cache: false,
    crossDomain: true,
    processData: true,

    success: function (data) {
    count++;
    if(count == fromStopsAr.length){your code or function call}
    $.each( matchRoutes, function(index, value) {
      $.each(data.response, function(key, data) {
          if(data.route_short_name.toString() == value) {
             jpFromStops[jpFromStops.length] = id + ":" + value;      
          }
      });   
     }); 
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      count++;
      if(count == fromStopsAr.length){your code or function call}
      alert("There is a problem");
    }
  });
}

【讨论】:

    【解决方案2】:

    你可以返回 promise 并使用 $.when

    function match() {
        var promises = [];
        // Array length is 5
        for(i=0; i < fromStopsAr.length; i++) {
            promises.push(getFromRoutesStopId(fromStopsAr[i]));
        }
        $.when.apply($, promises).then(function() {
            console.log("Match Array Output: " + jpFromStops.toString());
        });
    }
    
    function getFromRoutesStopId(id) {
       jpFromStops=[];
       tempAr = [];
    
      return jQuery.ajax({
        type: "GET",
        url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
        dataType: "jsonp",
        cache: false,
        crossDomain: true,
        processData: true,
    
        success: function (data) {
        $.each( matchRoutes, function(index, value) {
          $.each(data.response, function(key, data) {
              if(data.route_short_name.toString() == value) {
                 jpFromStops[jpFromStops.length] = id + ":" + value;      
              }
          });   
         }); 
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("There is a problem");
        }
      });
    }
    

    【讨论】:

    • 感谢您的回答,但是即使使用它,在 ajax 更新数组之前,我仍然将“匹配输出”设为空。
    【解决方案3】:

    在处理ajax 调用时,您需要等待每个调用都执行完毕。

    遵循这个模式:

    var jobs = [11, 12, 14, 15];
    function doTheJob() {
        if (jobs.length === 0) {
            alert('All jobs are done now.');
            complete();
            return;
        }
    
        var job_Id = jobs.pop();
        $.ajax({
            url: "/DoTheJob",
            complete: function () {
                doTheJob();
            }
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2020-08-07
      • 1970-01-01
      • 2021-12-28
      • 2019-05-21
      • 2013-12-19
      相关资源
      最近更新 更多