【问题标题】:Google Geocode API promise with large array带有大数组的 Google Geocode API 承诺
【发布时间】:2017-11-05 02:44:30
【问题描述】:

我的目标

使用 .map 遍历大型数组并使用 promise 查询 Google Geocoder API。

使用 Promise.all 在完成时将结果写入 .json 文件。

代码是针对node写的,数组是结构化的[[key:value],[key:value],....


我写的

var foo = (function() {
  let promises = airports.map(function(airport) {
    return geocoder
      .geocode(airport[1])
      .then(function(res) {
       let x = {
          ident: airport[0],
          address: res[0].formattedAddress,
          lat: res[0].latitude,
          long: res[0].longitude
        };
        return x;
      })
      .catch(function(err) {
        console.log(err);
      });
  });
  return Promise.all(promises)
    .then(function(promises) {
      console.log("promises resolved");
      fs.writeFile(
        path.join(__dirname, "/airports.json"),
        JSON.stringify(promises),
        "utf-8",
        function(err) {
          if (err) throw err;
          console.log("Done!");
        }
      );
    })
    .catch(function(err) {
      console.log(err);
    });
})();

问题

该代码适用于一个小数组(200 左右),但我需要的远不止这些。我认为这是 api 速率限制的问题,因为代码可以正常运行数百次迭代,然后返回大量 ETIMEDOUT 错误。

有没有办法减慢 map 的迭代速度,使其每秒说一个,以及在调用多个 Promise 的情况下,这在哪里适合?

我认为这会阻止我遇到的许多 ETIMEDOUT 错误。

谢谢。

【问题讨论】:

  • 你搜索过堆栈溢出吗?处理速率受限的 API 已被多次询问和回答 - 甚至还有一个名为 node-rate-limiter 的节点模块可能会有所帮助
  • 我理解速率限制器的概念,但我不明白它在哪里符合承诺。我是限制地图调用还是地理编码器调用?
  • 哦,我明白了,很抱歉假设您根本没有搜索

标签: javascript arrays promise


【解决方案1】:

这应该将请求限制为每秒 1 个

var foo = (function() {
    var delay = 1000; // sets the rate
    return airports.reduce((promise, airport) => promise
        .then(results => new Promise(resolve => setTimeout(resolve, delay, results)))
        .then(results => geocoder
            .geocode(airport[1])
            .then(function(res) {
                let x = {
                    ident: airport[0],
                    address: res[0].formattedAddress,
                    lat: res[0].latitude,
                    long: res[0].longitude
                };
                return results.concat(x);
            })
            .catch(function(err) {
                console.log(err);
            })
        ), Promise.resolve([])
    ).then(function(promises) {
        console.log("promises resolved");
        // ... etc
    })
})();

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 2014-03-18
    • 2016-11-12
    • 2017-12-14
    • 2019-01-05
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多