while循环api调用并将响应存储在nodejs中的数组中

问题描述 投票:0回答:1
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个回答
0
投票

fetch会返回一个诺言,一旦解决,该诺言将返回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)
});
© www.soinside.com 2019 - 2024. All rights reserved.