同步 Javascript 承诺超时以加班 Google 地理编码查询限制



我有一个包含>100 个地址的列表,并正在尝试向地理编码器发出请求以获取纬度和经度。在我得到所有结果的经度/经度之后,我将调用一个回调来对它做一些事情。谷歌的地理编码API对每秒的请求有时间限制,所以我想在每个请求之间设置1秒的延迟。我有下面的代码使用Javascript Promise调用Geocoder API,但看起来超时都是同时发生的。有没有办法使用承诺按顺序发生超时?

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

最新更新