为什么 Google 地方 AutocompleteService 回调没有被执行?

Why Google place AutocompleteService callback not getting executed?

我对地点 AutocompleteService() 的代码如下:

var strAddr = '';
if (address.value != "") {
    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({ input: address.value }, function (predictions, status) {
        console.log('1');
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            console.log('Original Response: ' + predictions[0].structured_formatting.secondary_text);
            strAddr = predictions[0].structured_formatting.secondary_text;
        }
    });
    console.log('strAddr: ' + strAddr);
    console.log('2');
}

console.log('3');

我在控制台中收到如下响应:

但应该是:

为什么回调没有按预期顺序执行?

不保证你能得到这个

  • 1
  • 原始回复://此处匹配地址>
  • strAddr: //匹配地址在这里
  • 2
  • 3

因为这个 ( new google.maps.places.AutocompleteService(); ) 是异步调用,你的回调可以按任何顺序调用

getQueryPredictions 函数是异步的(它可能通过 AJAX 发生)。所以你不能保证它会在紧随其后的代码之前完成。

例如对 getQueryPredictions 的调用可能需要 0.5 秒。因此,当发生这种情况时,这两行将能够立即执行:

console.log('strAddr: ' + strAddr);
console.log('2');

您不能依赖 strAddr 在等待 getQueryPredictions 响应的回调函数之外发生的任何代码中可用。