【问题标题】:How make a GET request inside a loop using async如何使用异步在循环内发出 GET 请求
【发布时间】:2020-03-10 01:43:28
【问题描述】:

我无法让获取请求在我拥有的循环中运行。代码本质上是这样的:

function getRequest(param){
   //Get request... then I save the response to a JSON file using fs.writeFile()
   //...
}
function run(){
   var arr = ['fee', 'foo', 'faa'];
   while(I need to update this for the duration of the program){
      arr.forEach((val) => {
         getRequest(val);
      }
   }
}

get 请求不会通过,因为循环不会等待它实际请求。我已经阅读了一些使用异步函数的潜在解决方案,但无法让它们工作。有什么建议么? TIA。

【问题讨论】:

    标签: javascript loops asynchronous get


    【解决方案1】:

    假设getRequest 返回一个Promise,你可以做Promise.all。这也意味着每个单独的请求不依赖于任何其他响应。它们都可以单独运行。

    Promise.all

    例子:

    function getRequest(param){
       //Get request... then I save the response to a JSON file using fs.writeFile()
       //...
    }
    function run(){
       var arr = ['fee', 'foo', 'faa'];
       const promises = [];
       while(I need to update this for the duration of the program){
          arr.forEach((val) => {
             promises.push(getRequest(val));
          }
       }
       return promises;
    }
    
    const promises = run(); // Array of Promises
    Promise.all(promises).then( response => {
      // ... 
    });

    【讨论】:

    • 感谢您的回复!在 getRequest 方法中返回一个 promise 有效,然后在 run 方法中调用它也有效——我只是像你说的那样写 const promises = run(); Promise.all(promises).then( response => {}); 来测试它们。这行得通......直到我把它放在一个循环中,每分钟循环一次,更新值。你知道为什么会这样吗?为了更清楚,这是我用于 while 循环的代码:while (true) { const promises = run(); Promise.all(promises).then(() => { console.log('HELLO'); }); }
    • 没关系,我通过使用 setInterval 而不是 while 循环来解决这个问题...
    • 我不建议在类似生产的场景中使用setInterval。请记得点赞/标记为答案
    • 你为什么这么说?我只是好奇。是的,对不起,我忘了标记为答案。它不会让我投票,因为我是新成员。
    • 如果您使用 setInterval,您会做出一个巨大的假设,即您的等待(间隔)时间足以完成请求。你永远不会得到这个完美的结果,所以由于糟糕的设计,你基本上会减慢你的应用程序的速度。 Promise.all 绝对是去这里的方式。 setInterval 的用例很少,所以我会尝试不使用它。
    【解决方案2】:

    你也可以试试

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

    如果您滚动到页面底部,还有一个 api 调用示例。

    【讨论】:

    • 感谢您的回复!我会记住这一点以备将来使用...
    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2020-12-20
    • 2019-07-21
    • 2019-08-05
    • 2020-02-18
    • 2017-11-15
    • 2017-11-22
    相关资源
    最近更新 更多