【问题标题】:Nodejs axios http request loopNodejs axios http请求循环
【发布时间】:2020-12-05 03:07:08
【问题描述】:

我对 Axios 和 foreach 循环有疑问。我的 Api 提供程序仅支持 5 个当代调用,所以我想一个一个调用,但是当执行此代码时,每个主体都不会等待完成调用函数并收到错误代码 429。如何解决这个问题?谢谢。

async function call(url) {
  var options = {
    method: 'GET',
    url: url,
    auth: {
      username: '*****',
      password: '*****'
    }
  };
  var response = await axios.request(options);
  print(response.data["Id"])
}

app.get('/save', async (req, res) => {
  var options = {
    method: 'GET',
    url: 'getListUser',
    auth: {
      username: '***',
      password: '***'
    }
  };
  var response = await axios.request(options);

  response.data["users"].forEach( async (val) => {
    console.log("ENTER");
    var url = 'getDetailUser' + val["id"];
    var res = await call(url); // <- How to wait finish this?
    console.log("EXIT")
  }, (err) => {
      console.log(err)
  })
  res.status(200).send("ok").end();
});

【问题讨论】:

    标签: javascript node.js axios


    【解决方案1】:

    仅供参考,Promise 无法使用涉及回调的循环,即forEach。或者,您可以使用for of

    try {
      for (const val of response.data['users']) {
        console.log("ENTER");
        var url = 'getDetailUser' + val["id"];
        var res = await call(url); 
        console.log("EXIT")
      }
    } catch (error) {
      console.log(error)
    }
    

    【讨论】:

      【解决方案2】:

      我会说@Ifaruki 的回答是正确的,只是稍作改动

      await Promise.allSettled(response.data["users"].map(val => {
         var url = 'getDetailUser' + val["id"];
         return call(url); 
      }))
      

      详情check the difference。在某些情况下 Promise.all 可能会起作用,但如果任何一个 Promise 失败,Promise.all 的整个结果将是拒绝。

      查看429 Too Many Requests可以解决代码429

      【讨论】:

        【解决方案3】:

        Promise.all() 方法

        await Promise.all(response.data["users"].map(val => {
           var url = 'getDetailUser' + val["id"];
           return call(url); 
        }))
        

        【讨论】:

          猜你喜欢
          • 2016-08-24
          • 2013-11-23
          • 1970-01-01
          • 2021-10-21
          • 2020-05-09
          • 1970-01-01
          • 2022-01-05
          • 2021-11-03
          • 2019-01-06
          相关资源
          最近更新 更多