【问题标题】:while loop api calls and storing response in array in nodejswhile循环api调用并将响应存储在nodejs中的数组中
【发布时间】:2020-02-20 07:03:38
【问题描述】:
var allData = []

function makeRequest(){
  fetch(url)
  .then(function(res) {
    return res.json();
  })
  .then(function(json){
    allData.push(...json.result)
    if (someCondition from json) {
      makeRequest()
    } 
  })
}
makeRequest();
console.log(allData)

上述函数会不断地调用api,直到API响应中满足某个条件。我希望将 API 调用的所有结果附加到一个名为 allData 的变量中。在上述状态下执行 allData 的 console.log 会导致一个空数组。如何等到所有 makeRequest 函数完成触发,然后 console.logging allData?

【问题讨论】:

    标签: node.js asynchronous while-loop fetch-api


    【解决方案1】:

    fetch 返回一个 Promise,一旦它解析将返回 res。承诺是异步的。试试这个

    function makeRequest(){
      return fetch(url)
      .then(function(res) {
        return res.json();
      })
      .then(function(json){
        allData.push(...json.result)
        if (someCondition from json) {
          return makeRequest() // return a promise to continue waiting
        } 
      })
    }
    makeRequest().then(function() { // waiting
      console.log(allData)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2013-12-12
      • 2013-08-19
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      相关资源
      最近更新 更多