簡體   English   中英

如何重新構建此for循環,以便在異步api調用完成之前不會發生下一次迭代

[英]How to re-structure this for loop so the next iteration doesn't happen until an asynchronous api call completes

因此,在下面,我們有一個類似於school [key] = value的數組。

for(key in schools) {
        geocoder = new google.maps.Geocoder();
        var address = schools[key];
        var org_code = key;
        geocoder.geocode({ 'address': address}, function(results, status) {
             //callback function
        })
}

我需要在回調函數中使用key / org_code,但是顯然for循環的迭代速度比geocode api調用完成的速度快,因此回調函數中使用了錯誤的密鑰。

我試圖使用array.shift將上面的內容重寫為一個函數,並在回調中使用該函數,但是我無法做到這一點……因為一件事,我無法使用該方法訪問鍵。

您可以使用閉包:

for(key in schools) {
    (function(key) {
        geocoder = new google.maps.Geocoder();
        var address = schools[key];
        var org_code = key;
        geocoder.geocode({ 'address': address}, function(results, status) {
            //callback function
        })
    })(key)
}

使用立即調用的函數表達式創建一個閉合,為每次迭代確定變量的范圍:

for (key in schools) {
    geocoder = new google.maps.Geocoder();
    var address = schools[key];
    var org_code = key;
    (function(address, org_code) {
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            //callback function
        })
    })(address, org_code);
}

使用閉包的另一個建議:

for(key in schools) {
    geocoder = new google.maps.Geocoder();
    var address = schools[key];
    var org_code = key;
    geocoder.geocode({ 'address': address }, function(org_code, address) {
        return function (results, status) {
            // use address and org_code here
        };
    }(org_code, address))
}

使用遞歸函數。 獲得關鍵-重新格式化學校陣列。

var geocoder = new google.maps.Geocoder();

function geocodeNext(sch) {
  var item = sch.shift();
  var address = item['address'];
  var key = item['key'];
  geocoder.geocode({ 'address': address}, function(results, status) {
    //do something with key
    geocodeNext(sch);
  })
}

var schools1 = [];
for var (key in schools) {
  schools1.push({'address': schools[key], 'key': key});
}

geocodeNext(schools1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM