遍历嵌套的Axios GET请求(分页)

时间:2020-07-30 17:36:11

标签: javascript rest axios

我正在查询包括分页的REST api。在进行初始查询后获得了总计数和每页最大数量后,我试图遍历总页数以获取所有项目。

const instance = axios.create({
    baseURL: 'https://api.com',
    headers: {'X-Application-Key': 'APPLICATION_KEY'}
});

instance.get('/trips')
    .then((response) => {
        const totalTrips = response.data.count;
        const totalPages = Math.ceil(totalTrips / response.data.max_per_page);
        let i;
        for (i = 0; i < (totalPages + 1); i++) {
            instance.get(`/trips?page=${i}`);
            console.log(response.data.results)
        };  
    })
    .catch(function (error) {
        console.log(error);
    })

这不起作用,因为'response'参数仍在引用初始查询,但是据我了解,所有.then块应处于同一级别而不是实际嵌套,因此我不确定如何实际循环浏览页面。完成此操作的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

这是一个稍微有些自负的响应,它使用async等待来处理多个异步请求。而且我认为您会希望使用诸如promise.all之类的函数,该函数可让您同时发出所有请求,并在所有http请求完成后处理响应。

const instance = axios.create({
    baseURL: 'https://api.com',
    headers: {
        'X-Application-Key': 'APPLICATION_KEY'
    }
});

getAlltrips();

async function getAlltrips() {
    try {
        const response = await instance.get('/trips');
        const totalTrips = response.data.count;
        const totalPages = Math.ceil(totalTrips / response.data.max_per_page);
        const promiseArray = [];
        for (let i = 0; i < (totalPages + 1); i++) {
            promiseArray.push(instance.get(`/trips?page=${i}`));
        };

        // promise.all allows you to make multiple axios requests at the same time.
        // It returns an array of the results of all your axios requests
        let resolvedPromises = await Promise.all(promiseArray)
        for (let i = 0; i < resolvedPromises.length; i++) {
            // This will give you access to the output of each API call
            console.log(resolvedPromises[i])
        }
    } catch (err) {
        console.log('Something went wrong.');
    }
}