简体   繁体   English

在javascript中将数组中填充的值从一个函数返回到另一个函数

[英]returning values populated in an array from one function to another in javascript

I'm doing a search through google maps, and I want to populate every location in an array. 我正在通过谷歌地图搜索,我想填充数组中的每个位置。 This allows me to sort properly since the API can lag at times and the JSON being returned may not be done correctly. 由于API有时会滞后并且返回的JSON可能无法正确完成,因此这使我可以正确排序。

This is using the Google Maps Places API. 这是使用Google Maps Places API。 Some code is left out to keep it brief. 省略了一些代码以使其简短。 I'm able to get the array to populate within a function, but when I try to pass it to another function it's blank. 我能够在函数中填充数组,但是当我尝试将其传递给另一个函数时,它为空。

   var liquorSearchParams = {
        location: latLong,
        rankBy: google.maps.places.RankBy.DISTANCE,
        types: ['liquor_store']
    };

    //Call the google maps service to perform the search 
    var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(liquorSearchParams, callback);

   //Set my blank array
    var allPlaces = [];

    function callback(results, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          //createMarker(results[i]);
          addPlaceToArray(results[i]);
          //this console.log just shows []
          console.log(allPlaces);
        }

      }
    }

    function addPlaceToArray(place) {
        var placeIdRequest = {
          placeId: place.place_id
        };
        service.getDetails(placeIdRequest, placeDetailCallback);
    };

    function placeDetailCallback(placeDetail, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            var destinationPoint = new google.maps.LatLng(placeDetail.geometry.location.k, placeDetail.geometry.location.B);
            var theDistance = google.maps.geometry.spherical.computeDistanceBetween(destinationPoint, latLong);

            allPlaces.push({name: placeDetail.name, latitude: placeDetail.geometry.location.k, longitude: placeDetail.geometry.location.B, address: placeDetail.vicinity, phone: placeDetail.formatted_phone_number, website: placeDetail.website, distance: theDistance});
            //this console.log returns the populated array that i want
            console.log(allPlaces);
            return allPlaces;
        }
    };

I expect that this is happening because allPlaces.push(...) happens in a callback which happens after the console.log(allPlaces) . 我希望发生这种情况是因为allPlaces.push(...)发生在console.log(allPlaces) 之后的回调中。

Here the actual sequence of events as far as I can tell: 据我所知,这里是实际的事件顺序:

  1. You retrieve some liquor stores 你找一些酒铺
  2. You iterate through them 您遍历他们
  3. For each store you: 对于每个商店,您:
    1. initiate a request for more details 发起更多细节请求
    2. immediately do a console.log(allPlaces) - which is empty because step 3 hasn't happened yet 立即执行console.log(allPlaces) -这是空的,因为步骤3尚未发生
    3. when the request for more details finishes, you push the details to the allPlaces array. 对更多详细信息的请求完成后,将详细信息推送到allPlaces数组。

What you need to do is do the console.log(allPlaces) once all the placeDetailCallback s have been completed. 您需要做的是在所有placeDetailCallback完成之后执行console.log(allPlaces) I recommend Async.js or something similar. 我推荐Async.js或类似的东西。

Using Async.js: 使用Async.js:

var liquorSearchParams = {
    location: latLong,
    rankBy: google.maps.places.RankBy.DISTANCE,
    types: ['liquor_store']
};

var allPlaces = [];

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    async.each(results, addPlaceToArray, function(err) {
        // this gets executed when all places have been added to allPlaces
        console.log(allPlaces);
    });
  }
}

//This is called for each item in the results array
//The done parameter is a callback you call when you are, well, done.
function addPlaceToArray(place, done) {
    var placeIdRequest = {
      placeId: place.place_id
    };

    var placeDetailCallback = function(placeDetail, status) {
        var destinationPoint = new google.maps.LatLng(placeDetail.geometry.location.k, placeDetail.geometry.location.B);
        var theDistance = google.maps.geometry.spherical.computeDistanceBetween(destinationPoint, latLong);

        allPlaces.push({name: placeDetail.name, latitude: placeDetail.geometry.location.k, longitude: placeDetail.geometry.location.B, address: placeDetail.vicinity, phone: placeDetail.formatted_phone_number, website: placeDetail.website, distance: theDistance});
        done(); //if an error occurred here, you can pass it to done
    };

    service.getDetails(placeIdRequest, placeDetailCallback);
};

//Call the google maps service to perform the search 
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(liquorSearchParams, callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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