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

时间:2014-11-12 20:44:13

标签: javascript arrays

我正在通过谷歌地图进行搜索,我想填充数组中的每个位置。这允许我正确排序,因为API可能会滞后,并且返回的JSON可能无法正确完成。

这是使用Google Maps Places API。遗漏了一些代码以保持简洁。我能够在一个函数中填充数组,但是当我尝试将它传递给另一个函数时,它是空白的。

   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;
        }
    };

1 个答案:

答案 0 :(得分:1)

我希望发生这种情况是因为allPlaces.push(...)发生在回调中,发生在 console.log(allPlaces)之后。

据我所知,事件的实际顺序如下:

  1. 你找回一些酒类商店
  2. 你遍历它们
  3. 对于每家商店,您:
    1. 发出更多详情请求
    2. 立即执行console.log(allPlaces) - 这是空的,因为步骤3尚未发生
    3. 当有关更多详细信息的请求完成时,您将详细信息推送到allPlaces数组。
  4. 您需要做的是在完成所有console.log(allPlaces)后执行placeDetailCallback。我推荐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);