首页 > 解决方案 > Javascript 数组空不空(Ajax)

问题描述

我正在尝试将 API google 发送给我的地址检索到一个数组中。问题是我刚刚收到一个包含所有元素的数组 empty(Address)。我尝试 async: false 我的 ajax,因为我的第一印象是异步是问题所在,但它什么也没做。如果你有任何想法会很好,谢谢。

输出 :

(4) [Array(0), Array(0), Array(0), Array(0)]
    0: Array(0)
        id: 9
        coord: "Rue des Haies 56, 6001 Charleroi, Belgique"
        length: 0
        __proto__: Array(0)
    1: [id: 10, coord: "43 Rue de Boulainvilliers, 75016 Paris, France"]
    2: [id: 11, coord: "Grand Place 22, 7000 Mons, Belgique"]
    3: [id: 12, coord: "28 Place Sébastopol, 59000 Lille, France"]
    length: 4
    __proto__: Array(0)

我的代码:

let geocoder = new google.maps.Geocoder;
$.ajax({
    type: "POST",
    url: "{{ path('url') }}",
    async : false,
    success: function (data) {
        let positions = JSON.parse(data);

        let allAddress = [];
        Array.from(positions).map((position, index) => {
            allAddress[index] = [];
            let latlng = {
                lat: parseFloat(position['latitude']),
                lng: parseFloat(position['longitude'])
            };

            let idPosition = position['id'];
            geocoder.geocode({'location': latlng}, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    let searchCoords = results[0]['formatted_address'];

                    setTimeout(function() {
                        allAddress[index]['id'] = idPosition;
                        allAddress[index]['coord'] = searchCoords;
                    }, 0);
                } else {
                    console.log("Geocode wasn't successful for the following reason : " + status);
                }
            });
        });
        console.log(allAddress);
    }
});

标签: javascriptphpajaxsymfony

解决方案


由于地理编码器是异步的,因此您需要使用 Promises 和 Promise all。下面是成功块

let positions = JSON.parse(data);
let allAddress = [];
// array to hold promises
const geoPromises = []
Array.from(positions).map((position, index) => {
  allAddress[index] = [];
  let latlng = {
    lat: parseFloat(position['latitude']),
    lng: parseFloat(position['longitude'])
  };

  let idPosition = position['id'];
  // push the promise into our array
  geoPromises.push(new Promise(function(resolve, reject) {
    geocoder.geocode({
      'location': latlng
    }, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        let searchCoords = results[0]['formatted_address'];
        allAddress[index] = {
          id: idPosition,
          coord: searchCoords,
        };
        // resolve the promise
        resolve(results)
      } else {
        console.log("Geocode wasn't successful for the following reason : " + status);
        // reject it 
        reject(status)
      }
    });
  }))
});

// wait for all the promises to complete
Promise.all(geoPromises).then(function(values) {
  // show your addresses
  console.log(allAddress);
}).catch(error => { 
  console.error(error.message)
});

推荐阅读