每件事都在我的代碼中作業,問題是this.loading=false在for()發送所有請求之前運行。
this.loading=false僅在for()完成發送所有請求后,如何才能執行?我希望你明白了。
methods:{
fileChange(event){
this.loading=true
//code
for(var i=0; i < tasks.length; i ){
//code
axios.post('/api/operation', data)
.then(response=>{
this.operations.push(name:response.data.name});
})
}
//i want to the bellow code to be executed after for() is finnished!
this.loading=false
},
},
uj5u.com熱心網友回復:
使用異步/等待
methods: {
async fileChange(event) {
this.loading = true
for (let i = 0; i < tasks.length; i ) {
const {data} = await axios.post('/api/operation', data) // << whats data?
this.operations.push({ name: data.name })
}
this.loading = false
},
},
uj5u.com熱心網友回復:
您的代碼確實設定this.loading為false在發送所有請求之后;您的意思是要在所有請求的所有回應都回傳后設定它嗎?我希望我正確理解了你的問題。
在這種情況下,您可以使用Promise.all()or Promise.allSettled():它們中的每一個都接受一個Promises陣列(例如,axios請求),并回傳另一個Promise在陣列中的所有承諾完成后用結果決議的陣列。
簡單來說,它允許您將許多承諾合并為一個,只有在它們全部完成后才完成。
例如:
methods: {
fileChange(event) {
this.loading = true;
// Send requests and store the Promises in an array.
// Each promise resolves to the response's `response.data.name` field.
const requestPromises = [];
for (var i = 0; i < tasks.length; i ) {
const promise = axios.post('/api/operation', data)
.then(response => response.data.name);
requestPromises.push(promise);
}
// Executed once all requests return a response
Promise.all(requestPromises)
.then(names => {
// Push all operation names into operations
this.operations.push(...names);
this.loadaing = false;
});
}
},
(注意:您可以使用Array.map()和async/使代碼更加優雅await)
Promise.all()和之間的區別在于Promise.allSettled()錯誤的處理 -Promise.all()如果傳遞給它的任何承諾失敗,則失敗(拒絕),而Promise.allSettled()始終決議為一個物件陣列,每個物件包含有關操作是否成功及其相關值的資料。
編輯:await在for回圈內使用會起作用,但效率非常低,因為您的代碼將等待一個請求結束,然后再發送下一個請求;如果您有 50 個請求要發送,并且每個請求大約需要 100 毫秒才能回傳,則使用awaitinsidefor將需要 50 * 100 = 5000 毫秒,或 5 秒才能結束;使用Promise.all/Promise.allSettled將使該數字接近 100 毫秒,因為所有請求都是一起發送的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395496.html
