如何跨多个页面获取数据

How to fetch data over multiple pages?

本文关键字:获取 数据 何跨多      更新时间:2023-09-26

我的项目基于 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将其存储在一种状态中。然后执行一个新请求,将总页数作为参数发送,并获取此总页数次数。通过这样做,我无法弄清楚存储每次迭代数据的语法。

一个可能的解决方案 - 这个想法是首先获取页数,然后进行适当数量的 API 调用,将每次调用的承诺推送到数组中。 然后,我们等待所有承诺解决,并对返回的数据执行某些操作。

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;
}