有条件地使第二个公理调用基于第一个公理发生



>我正在尝试这样做,以便我可以查看第一个 axios 调用返回的对象,如果为空,则继续执行第二个(如果它不为空,我将制作一条错误消息(

基本上,第二个 axios 调用应该只在 userStatus 对象为空时才发生。两个 axios 调用都独立工作,但是我怎样才能正确地完成这项工作,以便在对象为空时可以点击第二个调用?

目前,我在第一次 axios 调用时得到 200,在我的控制台中得到一个空的 userStatus 对象,但第二次调用没有发生

changeStatus: function(event) {
let user = this.auth_user;
axios.get('/user/' + user + '/status')
.then((response) => {
this.userStatus = response.data
})
if(this.userStatus.length < 1){
let data = {
id: event.id,
status: 'A'
};
axios.post('/status/change',data)
.then((response) => {
if (response.data.success == false) {
this.errors = [];
const errorLog = Object.entries(response.data.errors);
for (var i = errorLog.length - 1; i >= 0; i--) {
console.log(errorLog[i][1][0]);
this.errors.push(errorLog[i][1][0]);
}
}
})

}else{
console.dir('No');
}
},

问题是你的代码是同步执行的(基本上是逐行执行的(,而 axios 调用是同步的。因此,当您的第一个 axios 调用仍在后台执行时,语句if(this.userStatus.length < 1)在您的第一次调用返回之前被评估。

如果第二次调用以第一次调用的结果为条件,则需要第一次调用的.then()处理程序中进行第二次调用:

changeStatus: function(event) {
let user = this.auth_user;
axios.get('/user/' + user + '/status')
.then((response) => {
this.userStatus = response.data;
if(this.userStatus.length < 1) {
let data = {
id: event.id,
status: 'A'
};
axios.post('/status/change',data)
.then((response) => {
if (response.data.success == false) {
this.errors = [];
const errorLog = Object.entries(response.data.errors);
for (var i = errorLog.length - 1; i >= 0; i--) {
console.log(errorLog[i][1][0]);
this.errors.push(errorLog[i][1][0]);
}
}
});
} else {
console.dir('No');
}
});
},

最新更新