[工程架构思考-请求] 递归-ajax-请求获得后端分页数据

77 阅读1分钟
const http = {
  get() {
   async fetch_table_list(url='/table_list_api/', payload={}){
      return await axios.get(url, payload).then(res => {
        // next 为请求下一页数据的完整URL,由后端框架封装,直接请求即可
        if (!res.body.next) {
          return res.body.results
        }

        return http.get.fetch_table_list(res.body.next).then(lastResults => {
          return [].concat(res.body.results, lastResults)
        });
      });
    } // fetch_table_api end
  } // get end
}
// page
this.$store.dispatch('FetchHouseList');


// vuex
// 实现方式 1
actions: {
  FetchHouseList({ commit, state, dispatch }, payload) {
    return api.fetchHouseList(payload).then(res => {
      /* next page url */
      if (!res.nextPage) return res.results;
      return dispatch('FetchHouseList', { url: res.nextPage }).then(prev => {
        return [].concat(res.results, prev);
      });
    });
  } // FetchHouseList end
}

// 实现方式2
actions: {
  FetchHouseList({ commit, state, dispatch }, payload) {
    return new Promise((resolve, reject) => {
      api.fetchHouseList(payload).then(res => {
        /* next page url */
        if (!res.nextPage) {
          resolve(res.results);
          return
        }
        dispatch('FetchHouseList', { url: res.nextPage }).then(prev => {
          resolve([].concat(res.results, prev));
        });
      });
    });
  } // FetchHouseList end
}

相关链接:

  1. js的promise如何递归调用?
  2. #119 add retry for python requests