如何在多个页面上获取数据?

IT技术 javascript reactjs redux fetch redux-saga
2021-05-16 18:06:10

我的项目基于 React、redux、redux-saga、es6,我尝试从这个 API 获取数据:

http://api.dhsprogram.com/rest/dhs/data/BD,2000,2004,2007?&returnFields=CharacteristicLabel,Indicator,IndicatorId,Value&f=json

如您所见,此特定 API 调用显示的数据限制为每页 100 个数据,分布在 40 个页面上。

根据这个答案: http ://userforum.dhsprogram.com/index.php?t=msg&th=2086&goto=9591&S=Google 它说你可以将限制扩展到每页最多 3000 个数据。

但是,在某些情况下,我会执行超出该限制的 API 调用,这意味着我不会像这样接收所有数据:

export function fetchMetaData(countryCode: string, surveyYears: string) {
return (fetch('http://api.dhsprogram.com/rest/dhs/data/' + countryCode + ',' + surveyYears + '?returnFields=CharacteristicLabel,Indicator,IndicatorId,Value&f=json')
    .then(response => response.json())
    .then(json => json.Data.map(survey => survey)))
} 

所以我的问题是;鉴于我知道数据的总页数,从该 API 获取所有数据的最佳方法是什么。论坛链接中的答案建议循环访问 API。但是,我找不到正确的语法用法来执行此操作。

我的想法是进行一次 api 调用以获取总页数。然后使用 redux+redux-saga 将其存储在状态中。然后做一个新的请求,发送总页数作为参数并获取这个总页数次。通过这样做,我无法弄清楚为每次迭代存储数据的语法。

2个回答

一个可能的解决方案 - 想法是先获取页数,然后进行适当数量的 API 调用,将每次调用的 promise 推送到数组中。然后我们等待所有的 promise 得到解决,并对返回的数据做一些事情。

async function fetchMetaData() {

    const response = await fetch('apiUrlToGetPageNumber');

    const responses = await Promise.all(
        Array.from(
            Array(resp.data.pagesRequired),
            (_, i) => fetch(`apiUrlToSpecificPage?page=${i}`)
        )
    );
    
    // do something with processedResponses here

}
            
            

这是使用async/await. 这样做的total_pages好处是计数是动态的,因此如果在您处理请求时计数增加,它将确保您获得全部。

async function fetchMetaData() {
  let allData = [];
  let morePagesAvailable = true;
  let currentPage = 0;

  while(morePagesAvailable) {
    currentPage++;
    const response = await fetch(`http://api.dhsprogram.com/rest/dhs/data?page=${currentPage}`)
    let { data, total_pages } = await response.json();
    data.forEach(e => allData.unshift(e));
    morePagesAvailable = currentPage < total_pages;
  }

  return allData;
}