1

I have a tricky situation. I need to delay execution of a function until several functions have completed. While the following would work in a normal situation:

    $.when(foo1(), foo2(), foo3()).then(function(){
        //foo4();
    });

My situation is a little different. I don't want the functions passed to $.when() to execute immediately. foo1-3 will be executed at some point in the near future, by other methods. In other words, I want to execute foo1-3 manually, at a time of my choosing. Only after foo1-3 have executed (in no specific order) will foo4 run.

My intuition told me to dig into $.Deferred(), but I haven't quite found what I need. Any ideas?

2
  • 1
    You meant .then(foo4), right? Otherwise you're passing the value returned by foo4() to .then()... Commented Aug 7, 2012 at 18:44
  • I edited it to avoid confustion. But, yes, you are correct. Commented Aug 7, 2012 at 18:49

2 Answers 2

3

Have the fooX functions resolve deferreds which are passed to $.when.

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

function foo1() {
    // do normal work, then
    d1.resolve();
}

// same for other 2 functions

$.when(d1, d2, d3).then(foo4);

http://jsfiddle.net/mattball/nVFnv/

Sign up to request clarification or add additional context in comments.

Comments

2

Make a scoreboard variable that counts up as each function completes, then call foo4 after each function. foo4 should exit if the score has not counted up to the correct value.

2 Comments

Ok. Not bad. I had that idea myself. Was looking for something more elegant. But, "by hook or crook" is certainly an option.
The answer by Matt Ball is essentially your idea, just using deferred objects instead of a scoreboard variable. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.