【问题标题】:Javascript Array empty not empty (Ajax)Javascript 数组空不空(Ajax)
【发布时间】:2020-03-04 12:55:38
【问题描述】:

我正在尝试将 API google 发送给我的地址检索到一个数组中。问题是我刚收到 一个包含我所有元素的空数组(地址)。 我试图 async: false my 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);
    }
});

【问题讨论】:

  • 因为 geocoder.geocode 我们是异步的,不知道为什么你有一个 setTimeout 在那里。
  • 我想填充数组,但如果数组是异步的,我不能这样做,所以我尝试 setTimeout 我填充的每个元素。不知道够不够清楚...
  • 那个 setTimeout 不会对异步添加它做任何事情。问题是您正在循环所有内容并拨打所有电话,而您没有等待所有电话完成。你需要用 promise all 来研究 promise。
  • 好的,我会阅读文档并尝试这样做。
  • 我有两分钟的时间,所以写了要做什么

标签: javascript php ajax symfony


【解决方案1】:

由于地理编码器是异步的,因此您需要使用 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)
});

【讨论】:

  • 我尝试了你的解决方案,但我总是相同的答案是空数组不为空:( ``` (4) [Array(0), Array(0), Array(0), Array( 0)] 0: Array(0) id: 9 coord: "Rue des Haies 56, 6001 Charleroi, Belgique" 长度: 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 "] 长度:4 proto: Array(0) ```
  • 我有一个数组(0)到数组中,数组(0)不为空,但长度为空
  • 我编辑了您要添加属性的部分
  • 感谢它的工作,你是对的。我还有很多东西要学:)
猜你喜欢
  • 2015-01-27
  • 2010-09-20
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 2018-06-07
  • 2019-03-14
  • 2016-08-06
相关资源
最近更新 更多