同步 Javascript 承诺超时到超时 Google Geocode querylimit

Synchronous Javascript Promise with timeouts to overtime Google Geocode querylimit

我有一个超过 100 个地址的列表,我正在尝试向 Geocoder 发出请求以获取纬度和经度。在我得到所有结果 lat/longs 之后,我将调用一个回调来对其进行处理。 Google's geocoding API 对每秒的请求有时间限制,所以我想在每个请求之间设置 1 秒的延迟。我有下面的代码使用 Javascript Promise,它调用 Geocoder API,但看起来超时都是同时发生的。有没有办法使用 Promises 使超时按顺序发生?

function geoCodePromise(address) {
  let promise = new Promise(function(resolve, reject) {

    geocoder.geocode({
      'address': address
    }, function(res, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        setTimeout(function() { resolve(res[0].geometry.location); }, 1000);
      } else {
        setTimeout(function() { reject(status); }, 1000);
      }
    });
  });

  return promise;
}

// long list of addresses. Listing two here for example
let addresses = ["1340 Lincoln Blvd, Santa Monica, CA 90401", "223 N 7th Ave, Phoenix, AZ 85007"]

let promises = [];
for (let i=1; i < addresses.length; i++) {
  promises.push(geoCodePromise(addresses[i]));
}

Promise.all(promises).then(function(results) {
  // callback to do something with the results
  callbackfunc(results)
})
.catch(function(err) {
  console.log(err);
})

尝试将 i 传递给 geoCodePromise 以在 setTimeout 时长乘以 1000;删除 reject 处的 setTimeout;在 for 循环

调用 geoCodePromise
function geoCodePromise(address, i) {
  let promise = new Promise(function(resolve, reject) {   
    geocoder.geocode({
      'address': address
    }, function(res, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        setTimeout(function() { resolve(res[0].geometry.location); }, 1000 * i);
      } else {
        reject(status);;
      }
    });
  });   
  return promise;
}

// long list of addresses. Listing two here for example
let addresses = ["1340 Lincoln Blvd, Santa Monica, CA 90401", "223 N 7th Ave, Phoenix, AZ 85007"]

let promises = [];
for (let i = 1; i < addresses.length; i++) {
  promises.push(geoCodePromise(addresses[i], i));
}

Promise.all(promises).then(function(results) {
  // callback to do something with the results
  callbackfunc(results)
})
.catch(function(err) {
  console.log(err);
})

function geoCodePromise(a, i) {
  let promise = new Promise(function(resolve) {
    setTimeout(function() {
      resolve([a, i])
    }, 1000 * i)
  })
  return promise
}
let addresses = "abcdefg".split("");
let promises = [];

for (let i = 0; i < addresses.length; i++) {
  promises.push(geoCodePromise(addresses[i], i));
}

Promise.all(promises).then(function(results) {
  // callback to do something with the results
  callbackfunc(results)
})
.catch(function(err) {
  console.log(err);
});

function callbackfunc(results) {
  console.log(JSON.stringify(results, null, 2))
}