等待它完成回调函数的执行

鲁克米·帕特尔

我已经编写了从 Google Place API 获取 Google 地点信息的代码。我只想displayHTML()在系统完成循环中的所有 AJAX 调用时调用。

var placeid_json = [{
  "placeid": 'ChIJcSlz1vtz6lIR6rXex3J9PFE',
  "url": "/locations/northway-pharmacy-broadway"
}, {
  "placeid": 'ChIJ515pxC5x6lIR8MKrpu1a6GY',
  "url": "/locations/northway-pharmacy-brothers"
}, ];

function getLocationPerServicesFirstTime() {
  console.log("getLocationPerServicesFirstTime called");
  var counter = 0;
  for (i = 0; i < placeid_json.length; i++) {
    var service = new google.maps.places.PlacesService(map);
    // var placeId = placeid_json[i].placeid;

    googlePlacePromises.push(service.getDetails({
      placeId: placeid_json[counter].placeid
    }, function(result, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        console.log(status);
        return;
      }

      storeLocation = {
        placeId: placeid_json[counter].placeid,
        url: placeid_json[counter].url,
        lat: result.geometry.location.lat(),
        lng: result.geometry.location.lng(),
        result: result,
      }

      storesInfo.push(storeLocation);

      if ((placeid_json.length - 1) == counter) {
        // console.log(storesInfo);
        // console.log(counter);
        // displayHTML();
      }
      counter++;
      console.log("Google Place API called!");
    }));
    // console.log(googlePlaceService);
    // googlePlacePromises.push(googlePlaceService);
  }

  $.when.apply(null, googlePlacePromises).done(function() {
    console.log(storesInfo.slice());
    console.log("All ajax call completed");
    displayHTML();
  });

  console.log(googlePlacePromises);
}
蒂莫菲·冈察洛夫

看来你应该使用 Promise.all()

Promise.all(googlePlacePromises).then(function(results) {
  console.log('resolved promises: ', results);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章