Reputation: 189
So i have this array of stuff that it needs to be updated, but since async:false was deprecated and it needs to be one by one to show the progress of the update, is any way to do this with ajax.success?, example:
progressUpdate(stuff[0].name, 100 / stuff.length)
for(var f = 0; f < stuff.length; f++){
$.ajax({
type: "PUT",
global: true,
url: '/stuffs/'+stuff[f].id+'.json',
contentType: 'application/json',
dataType: 'script',
data: JSON.stringify({stuff:{set: 1}, _method:'put'})
});
//Wait here to finish updating, then continue increase the progressbar
progressUpdate(stuff[f].name, 100 / stuff.length)
}
I try to put the progressUpdate() inside the success but is not in the order of the array, since it updates when it recives the callback, some of the posterior elements finish before the previous element, like this
....
.success: funcion(){
progressUpdate(stuff[f].name, 100 / stuff.length)
}
....
Is there any way to do this progression in order?
Upvotes: 1
Views: 678
Reputation: 168
One way to make it update the stuff in order would be to call for the next update only on the success of the previous. Something like this
function updateStuff(f){
if(f < stuff.length){
ajax stuff ...
success: funcion(){
progressUpdate(stuff[f].name, 100 / stuff.length)
updateStuff(f+1);
}
}
}
And call updateStuff(0) to start the recursion.
Upvotes: 0
Reputation: 1430
What about this ?
do_job(stuff, 0); // Launch first job
function do_job(stuff, index) {
if (index < stuff.length)
{
$.ajax({
type: "PUT",
global: true,
url: '/stuffs/'+stuff[f].id+'.json',
contentType: 'application/json',
dataType: 'script',
data: JSON.stringify({stuff:{set: 1}, _method:'put'}),
success: function(data) {
// Job finished, let's begin the next one
progressUpdate(stuff[index].name, 100 / stuff.length)
do_job(stuff, index + 1); // actual index (your variable "f") + 1
}
});
} else {
// every stuff is finished
}
}
Upvotes: 2