简体   繁体   English

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

[英]Looping through nested Axios GET request (pagination)

I'm querying a REST api which includes pagination.我正在查询包含分页的 REST api。 After an initial query which gets total count and max per page, I'm trying to loop through total pages to get all of the items.在获得总计数和每页最大值的初始查询之后,我试图遍历总页数以获取所有项目。

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

This isn't working since the 'response' argument is still referencing the initial query, but it's my understanding that all.then blocks should be on the same level and not actually nested, so I'm not sure how to actually loop through the pages.这不起作用,因为“响应”参数仍在引用初始查询,但我的理解是 all.then 块应该在同一级别而不是实际嵌套,所以我不确定如何实际循环页。 What is the proper way to accomplish this?实现此目的的正确方法是什么?

Here is a slightly opinionated response, using async await to handle the multiple asynchronous requests.这是一个有点自以为是的响应,使用 async await 来处理多个异步请求。 And I think you'll want to use a function like promise.all, which allows you to make all the requests at the same time, and handle the response when all the http requests have completed.而且我认为您会想要使用 function 之类的 promise.all,它允许您同时发出所有请求,并在所有 Z80791B3AE7002CB88C246876D9FAA8FZ 请求完成后处理响应。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM