【问题标题】:How to get data with axios from all api pages?如何使用 axios 从所有 api 页面获取数据?
【发布时间】:2020-12-17 14:39:34
【问题描述】:

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

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

【问题讨论】:

  • while 是一个无限循环,因为您将异步代码与同步代码混淆了
  • @TKoL 请告诉我,我该怎么做才能更好?我是初学者

标签: javascript api vue.js axios


【解决方案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 函数一起添加,并在最后返回整个列表。

【讨论】:

  • 没问题。我在自己的项目中一直使用这种模式。
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 2020-11-18
  • 2021-09-05
  • 1970-01-01
  • 2020-09-11
  • 2019-12-15
  • 2013-11-24
  • 2020-02-09
相关资源
最近更新 更多