I have some code that completes a distinct set of operations in a chain. The set of operations, itself, is executed in a loop. Because of the nature of the system I'm dealing with, the operation sets need to be executed synchronously (i.e., the next set of operations cannot execute before the first set is finished). Asynchronous execution can throw off the remote processor (not in my control), and cause the code to fail. Right now, the only way I've been able to get this to work is to use alert boxes, which is truly lame and not an option. I've tried:
- using $.ajax, and setting the async to false
- using a sleep function
- alert boxes (used in desperation)
Here is the code - Any thoughts?:
$('input:checked').each(function(index){
//get the item's location id
var currentInput = $(this).val();
var copyUser = function(){$.get(urlCopyPrefix + currentInput + urlSuffix);}
var moveUser = function(){$.get(urlMovePrefix + moveLocation + urlSuffix);}
var cleanup = function(){
var newSibling = $('#module-' + moveLocation);
newSibling.before('<li>New Line</li>');
alert('done');
}
/* --> THIS IS THE CODE IN QUESTION <-- */
$.when(copyUser()).pipe(moveUser).then(cleanup);
});
I think you'll have to stop using
.each()
because it runs the whole iteration right away and you don't want to do that.Here's one way to do it, using completion functions and a local function:
Or, using deferreds:
A note on your deferreds: You have to pass function references, not function calls. That means you pass the function name without parens.