如何使用axios从所有api页面获取数据?

时间:2020-08-28 16:19:44

标签: javascript api vue.js axios

我在做什么错?我想从api中的所有页面获取数据。添加了一段时间后它停止工作,但是我不知道如何以不同的方式启动页面循环!

    getCustomers: function() {
        let url = '/crm/customer/';
        return axios.get(url).then((response) => {
           this.customers = response.data.results;
           if (this.customers.length === 100) {
                let i = 2;
                axios.get('/crm/customer/?page=' + i).then((response) => {
                  this.c = response.data.results;
                  i += 1;
                  for (let item of this.c.values()) {
                      this.customers.push(item);
                  }
                  while (this.c.length === 100) {
                      axios.get('/crm/customer/?page=' + i).then((response) => {
                        this.c = response.data.results;
                        i += 1;
                        for (let item of this.c.values()) {
                          this.customers.push(item);
                        }
                      }).catch( error => {}).finally(() => (global_waiting_stop()));
                  }
                }).catch( error => {}).finally(() => (global_waiting_stop()));
           }
         }).catch( error => {}).finally(() => (global_waiting_stop()));
    },

1 个答案:

答案 0 :(得分:1)

首先,我要使用一个名为getPageOfResults的异步函数:

async function getPageOfResults(page) {
    const response = await axios.get('/crm/customer/?page=' + page);
    return response.data.results; // .results.values()? I don't know
}

然后,在另一个异步函数中,您可以具有一个执行所需操作的循环:

async function getAllResults() {
    const customers = [];
    let lastResultsLength = 100;
    let page = 1;
    while (lastResultsLength === 100) {
        const newResults = await getPageOfResults(page);
        page++;
        lastResultsLength = newResults.length;
        customers = customers.concat(newResults);
    }
    return customers;
}

因此,您有一个变量来跟踪所访问的页面,并且不断获取新页面,直到获得结果少于100个的页面为止。

您要将所有结果与concat函数一起添加,并在末尾返回整个列表。