Kie*_* Vu 1 javascript fetch reactjs redux redux-saga
我的项目基于React,redux,redux-saga,es6,我尝试从此API提取数据:
如您所见,此特定的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)))
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是;考虑到我知道数据的总页数,从此API获取所有数据的最佳方法是什么。论坛链接中的答案建议循环浏览API。但是,我找不到正确的语法用法来做到这一点。
我的想法是进行一次api调用以获取页面总数。然后使用redux + redux-saga将其存储在状态中。然后执行一个新请求,将总页数作为参数发送,并获取此总页数。通过这样做,我无法弄清楚存储每次迭代数据的语法。
小智 7
这是使用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;
}
Run Code Online (Sandbox Code Playgroud)
一个可能的解决方案-这个想法是先获取页面数,然后进行适当数量的API调用,将每个调用中的promise推入数组。然后,我们等待所有承诺解决,并对返回的数据进行处理。
function fetchMetaData() {
let pagesRequired = 0;
fetch('apiUrlToGetPageNumber')
.then(resp = > {
const apiPromises = [];
pagesRequired = resp.data.pagesRequired;
for (let i=pagesRequired; i>0;i--) {
apiPromises.push(fetch('apiUrlToSpecificPage?page = ' + i));
}
Promise.all(apiPromises)
.then(responses => {
const processedResponses = [];
responses.map(response => {
processedResponses.push(response);
}
// do something with processedResponses here
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4578 次 |
| 最近记录: |