首页 > 解决方案 > axios同步取数据的问题

问题描述

我正在使用 4 个 Axios.get 语句,这些语句用于一次从 4 个不同的来源获取数据。在第一次获取尝试时获取它们没有问题 - 服务正在工作并正确显示结果。据我了解,我的问题是,当我尝试使用其他 axios.get 重写结果时,它首先呈现,然后获取数据。

下面是两个 Axios.gets 的代码,其中 getCashboxBonusNDS() 在 getCashboxuserBonusNDS() 之后会导致错误。并在更改时更改 Api 服务的 switch 语句

getCashboxuserBonusNDS = (dateFrom, dateTo, client) => {
    Axios.get('/api/report/sales/ndscashboxuser', {
        params: { dateFrom, dateTo, client }
    }).then(res => res.data)
        .then((salesResultNDS) => {
            this.setState({ salesResultNDS, isLoading: false });
        })
        .catch((err) => {
            console.log(err)
        })
};

getCashboxBonusNDS = (dateFrom, dateTo, client) => {
    Axios.get('/api/report/sales/ndscashbox', {
        params: { dateFrom, dateTo, client }
    }).then(res => res.data)
        .then((salesNDS) => {

            const temp = _.mapValues(_.groupBy(salesNDS, 'point'), list => list.map(bs => _.omit(bs, 'point')));

            const salesResultNDS = Object.keys(temp).map(key => {
                return {
                    point: key,
                    cashboxesNDS: temp[key]
                }
            });
            this.setState({ salesResultNDS, cashboxSalesResultNDS: salesNDS, isLoading: false });
        })
        .catch((err) => {
            console.log(err)
        })
};

 switch (filter.value) {
        case 'cashboxFiz': {

            if(filterType.value==='cashbox'){
                this.getCashboxBonus(dateFrom, dateTo, "fiz");
                this.getCashboxBonusNDS(dateFrom, dateTo, "fiz")
            }else{
                this.getCashboxuserBonus(dateFrom, dateTo, "fiz");
                this.getCashboxuserBonusNDS(dateFrom, dateTo, "fiz")
            }
            break;
        }
        case 'cashboxJur': {

            if(filterType.value==='cashbox'){
                this.getCashboxBonus(dateFrom, dateTo, "jur");
                this.getCashboxBonusNDS(dateFrom, dateTo, "jur")
            }else{
                this.getCashboxuserBonus(dateFrom, dateTo, "jur");
                this.getCashboxuserBonusNDS(dateFrom, dateTo, "jur")
            }
            break;
        }

        default:
            console.log("Error: filter not detected")
    }

唯一的错误信息:TypeError: Cannot read property 'reduce' of undefined

标签: reactjsaxios

解决方案


可以将 Promise 链接在一起,以确保特定请求始终按顺序执行(同步)。我在下面提供了一个示例。

const get = (endpoint = '/', params = {}) => {
  // return axios promise
  return axios({
    method: 'get',
    url: apiHost + endpoint,
    headers: { 'Authorization': 'Token ' + this.state.token },
    params: params,
  });
};

get('/api/some-endpoint/')
  .then((response) => {
    console.log(response);
    //return next promise
    return get('/api/another-endpoint/');
  }).then((response) => {
    console.log(response);
    // return next promise
    return get('/api/yet-endpoint');
  }).then((response) => {
    console.log(response);
    // return next promise
    return get('/api/last-endpoint/');
  }).then((response) => {
    console.log(response);
    // finished, no more promises left in the chain
  })
  .catch(function (error) {
    console.log('Error getting data', error);
  });

推荐阅读