简体   繁体   中英

Javascript async functions with Google Maps API

I would like to populate a Javascript dictionary with restaurant chain names as keys and an object consisting of latitude and longitude as the values. I have the following code:

// create symbol table of name-coordinate pairs
var baseLocation = new google.maps.LatLng(window.latBase, window.lngBase);
var dict = {};
var service = new google.maps.places.PlacesService(window.map);

for (var i = 0; i < arr.length; i++) {
    var singleChain = arr[i];
    console.log(singleChain);
    var request = {
        location: baseLocation,
        radius: '5000',
        query: singleChain
    };

    service.textSearch(request, function(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            dict[singleChain] = {
                lat: results[0].geometry.location.lat(),
                lng: results[0].geometry.location.lng()
            }
        }
    })

    // end for loop
}

The problem is, I now realize that the Google API request is not asynchronous, so each request is actually being made on only the last chain in arr[], ending up with a single-entry dictionary. What is the best way to implement an asynchronous function to get the desired functionality?

Instead of using a for loop which has an asynchronous function, you can go for a different approach. you can use recursive functions.

For example :

 let arr = [1, 2, 3 , 4, 5]; function doSometing(i) { if(i >= arr.length) { return false; } setTimeout(function() { /* Do your computations */ console.log(arr[i]); doSometing(i + 1); }, 2000); } doSometing(0); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM