我正在使用4个Axios.get语句,这些语句可立即从4个不同的源中获取数据。在第一次获取尝试中获取它们没有问题-服务正在运行并正确显示结果。据我了解,我的问题是,当我尝试使用其他axios.get重写结果时,它首先呈现,然后获取数据。
下面是两个Axios.gets的代码,其中,如果getCashboxBonusNDS()次于getCashboxuserBonusNDS(),则会导致错误。并在更改时更改更改Api服务的语句
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:无法读取未定义的属性“ reduce”
答案 0 :(得分:0)
可以将诺言链接在一起,以确保始终按顺序(同步)执行特定请求。我在下面提供了一个示例。
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);
});