[英]conditionally make the 2nd axios call happen based on a first
我正在嘗試這樣做,以便我可以查看第一個 axios 調用返回的 object,如果為空,則繼續到第二個(如果它不為空,我將制作錯誤消息)
基本上,只有當 userStatus object 為空時,才會發生第二次 axios 調用。 兩個 axios 調用都獨立工作,但是如果 object 為空,我如何才能正確地進行這項工作,以便我可以打第二個電話?
目前我在第一個 axios 調用和一個空的 userStatus object 在我的控制台中得到 200 但第二個調用沒有發生
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 .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');
}
});
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.