Let’s say I use $.get to receive an array of user IDs.
Let us then presume that I want to go through all those user IDs (example: [13, 14, 15, 23, 34, 56]) and retrieve certain information on each, then populate a textfield based on the results, and move on to the next one.
$.each(array_of_users, function(i, id) {
$.get("/somefunction", {id}, function(data){
appendToField(data);
}, "json");
});
How would I make it so that these loops don’t all happen at once and then wait for the result together asynchronously, as they do now, but one by one? That is, I want to stop the loop from going onto the next element until the ajax requests says it’s fine to do so.
What is the best way to approach this without using delays or timeouts, but actual responses from the function doing the processing?
Cheers
Edit:
The stylish representation of a “command-prompt” look is important to me, which is why I would like the textarea to receive messages one by one as the entries are processed. I am aware I could do this via PHP much easier and without the hassle or potential JS breaks, but I would like to do it stylishly via JS to simulate this “console” look, as in:
10:01:33: User 13 processed: Changed expiry date to 13.02.2011.
10:01:34: User 16 not processed: Target immune to system changes..
10:01:34: User 17 not processed: Target immune to system changes..
10:01:35: User 23 processed: Changed expiry date to 19.02.2011.
etc..
Edit2:
I just found this brilliant little plugin which lets me do exactly what I want. However, I cannot find the means to stop the queue once it’s been started. This is now a new issue. Any ideas, anyone? Reloading the page works, naturally, but I would like it to freeze in place as soon as I hit the Stop button so that the user can simply copy the entire report right out of the textfield.
Basically, use the first
.get()to retrieve the list of values (array_of_users). Using this list, pass them off to a “worker” function that takes the first element, works with it, then sends the remaining elements off to do the same. Keep going until there are no more entries to process. (think of it like a FIFO Queue)EDIT: used variables / GET paths similar to what you mentioned in your initial question.