0

Attempting to use $.Deferreds in place of setTimeOut which I was using prior. I'm running into an issue, as writer() isn't actually done, because the $.each are still looping at the time printer() is called.

I haven't seen an example of $.Deferreds with loops. Obviously the below is wrong, and I'm betting it has to do with the resolve - any help would be appreciated.

$.when( writer() ).done(function() {
    printer();
});


function writer(){
    var deferred = new $.Deferred();
    if(x){
        $("a").each(function () {...});
    }
    if(y){
        $("img").each(function () {...});
    }
    if(z){
        $("div").each(function () {...});
    }
    deferred.resolve();
    return deferred.promise();

}

function printer(){...}
Jason
  • 7,612
  • 14
  • 77
  • 127
  • Think about it, you are ALWAYS resolving it before you return it, so the `.done` will always happen immediately after calling `writer`, regardless of whether or not whatever asynchronous events inside of your `.each` are done. If you aren't doing any asynchronous work inside the `$.each`, you don't need deferred objects. – Kevin B Mar 12 '13 at 14:30
  • @KevinB - that's exactly what I figured was happening, just not sure how to return multiple deferreds before triggering printer() – Jason Mar 12 '13 at 14:35
  • Unrelated, but why are you calling `.each()` on a jQuery object that will only ever contain at most one element? – Anthony Grist Mar 12 '13 at 14:36
  • I would have to know what the asynchronous event is, `$.each` is synchronous meaning `printer` can't run until all of the `$.each` are done. – Kevin B Mar 12 '13 at 14:37
  • @AnthonyGrist - dummied it for the code, bad example - will edit. – Jason Mar 12 '13 at 14:44
  • Looks like it might be straightforward synchronous code, in which case Deferred(s) are not required. If I'm wrong and the asynchronicity is AJAX-induced, then you should build one (large) AJAX request and respond to its response with one simple `jqXHR.done(...)`. – Beetroot-Beetroot Mar 12 '13 at 22:34

1 Answers1

0

Assuming ... inside of the .each is doing an asynchronous event, you'll need all of those asynchronous events to return a deferred object that you can pass into a $.when to trigger your resolve.

Also, at the top of your code, you don't need $.when for a single callback, just do writer().done(function(){...})

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • see updated - $.each is wrapped in an if - so how to return the deferred in the $.each and ensure all are returned that are true? – Jason Mar 12 '13 at 14:33