【问题标题】:How can i defer the last line of code which follows after AJAX request?如何推迟 AJAX 请求之后的最后一行代码?
【发布时间】:2016-09-08 22:20:08
【问题描述】:

我有以下代码,它从 php 脚本中获取地址列表,然后向谷歌地图发出 ajax 请求,然后创建标记并更改缩放以适应标记。

var bounds = new google.maps.LatLngBounds();
$.getJSON('/dmvfinder/dmvsearch.php', {zipcode: zipcode, state: state, city: city}, function (addresses) {
	addresses.forEach(function(address){
		$.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {address: address}, function(data){
				var p = data.results[0].geometry.location;
				var latlng = new google.maps.LatLng(p.lat, p.lng);
				var marker = new google.maps.Marker({
					position: latlng,
					map: map
				});
				bounds.extend(latlng);
		});
	});
});
map.fitBounds(bounds);

据我了解,代码的问题是 fitBounds 方法在 ajax 完成之前触发并且“边界”被填充。我怎么可能在这里推迟最后一行代码?

提前谢谢你!

【问题讨论】:

  • 将该行代码放在回调函数中,而不是在它之外。
  • @Pointy - 不会等待内部 getJSON 完成,对吗
  • 您希望您的标记出现并且边界是逐个调整还是一次性调整?
  • @JaromandaX 不,这是真的,它不会。
  • 由于帖子现在重复,这里有一个更简单的解决方案pastebin.com/xE7GxMMs

标签: javascript ajax callback


【解决方案1】:

你需要改变两件事

  1. 累积来自address.forEach 的所有承诺 - 将其更改为map 并确保为return $.getJSON(..)。这将为您提供一系列延迟。
  2. 使用 $.when 等待它们全部完成 - 因为这需要参数,而不是数组,您可以在 1) 的数组上使用 $.when.apply(..)

像这样:

var bounds = new google.maps.LatLngBounds();
$.getJSON('/dmvfinder/dmvsearch.php', {zipcode: zipcode, state: state, city: city}, function (addresses) {
    // 1. Accumulate all the promises into an array
    var allPromises = addresses.map(function(address){
        return $.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {address: address}, function(data){
            var p = data.results[0].geometry.location;
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });
            bounds.extend(latlng);
        });
    });
    // 2. wait for them all to complete
    $.when.apply($,allPromises).then(function(){
      map.fitBounds(bounds);
    })
});

【讨论】:

  • 很好,回答,但我无法正确理解 allDeferreds,你能解释一下吗?
  • @ParagBhayani 查看Array.map 的作用,以及$.getJSON 的返回类型。
  • 很好 - 我自己会省去 allDeferreds var ...$.when.apply($, addresses.map(function(address) { ...}).then(...); - 但是当你的答案弹出时我正在打字:p跨度>
  • @JaromandaX 这将是冗长而笨拙的代码行。我更愿意看看它在做什么——尤其是在解释答案时。即 - 它匹配我的 1. & 2.
猜你喜欢
  • 2014-11-20
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多