How to fetch data over multiple pages?

前端 未结 2 802
时光说笑
时光说笑 2021-01-27 00:50

My project is based on React, redux, redux-saga, es6 and I try to fetch data from this API:

http://api.dhsprogram.com/rest/dhs/data/BD,2000,2004,2007?&returnFields=C

2条回答
  •  时光取名叫无心
    2021-01-27 01:40

    A possible solution -the idea is to get the number of pages first, then make the appropriate number of API calls, pushing the promise from each call into an array. We then wait for all the promises to resolve, and do something with the returned data.

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

提交回复
热议问题