every thing work in my code, the problem is that this.loading=false
run before the for()
is done sending all the requests.
How can make this.loading=false
get executed only after the for()
finishes sending all the requests ?
i hope you got the idea.
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
},
},
CodePudding user response:
use async/await
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
},
},
CodePudding user response:
Your code does set this.loading
to false
after all requests are sent; did you mean you want it to be set after all responses from all requests have returned? I hope I understood your question correctly.
In that case, you can use Promise.all()
or Promise.allSettled()
: each of them takes an array of Promise
s (for example, axios
requests), and returns another Promise
which resolves with the results once all the promises in the array finish.
In simpler words, it allows you to combine many promises into one, which completes only once they all completed.
For example:
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;
});
}
},
(Note: you can make the code much more elegant using Array.map()
and async
/await
)
The difference between Promise.all()
and Promise.allSettled()
is regarding the handling of errors - Promise.all()
fails (rejects) if any of the promises passed into it fail, while Promise.allSettled()
always resolves to an array of objects, each containing data about whether the operation succeeded and its associated values.
Edit: using await
inside the for
loop will work, but it's highly inefficient, as your code will wait for one request to end before sending the next; if you have 50 requests to send, and each takes approximately 100ms to return, using await
inside for
will take 50 * 100 = 5000 ms, or 5 seconds to end; using Promise.all
/Promise.allSettled
will keep that number close to 100ms, as all requests are sent together.