0

I have 3 JS functions :

func1 ()
{
    $.ajax(...,callback1)
}


func2 ()
{
    $.ajax(...,callback2)
}


func3 ()
{
    $.ajax(...,callback3)
}

They are executed like this :

func1();
func2();
func3();

Question how can I execute mySummaryCallback() after all 3 are done ?

NB

I could use a closure callback function which increase a value and then execute. but I can't touch the ajax callback functions. (https://stackoverflow.com/a/2911891/859154)

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

5 Answers5

3

Use $.when() to do this for all your methods need to return the promise object back to the caller

func1() {
    return $.ajax(..., callback1)
}


func2() {
    return $.ajax(..., callback2)
}


func3() {
    return $.ajax(..., callback3)
}

$.when(func1(), func2(), func3()).done(function () {
    //all are success
}).fail(function(){
    //atleast one failed
}).always(function(){
    //all are completed
})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Your edit helped me.. so `when` signals when they all **resolved** and then they (all results) **filtered to one** callback done/fail/always....right ? – Royi Namir Sep 23 '13 at 11:18
  • @RoyiNamir yes... the `always` is called in either case... along with `done` and `fail` – Arun P Johny Sep 23 '13 at 11:21
  • I guess always() will be fired even, e.g, only first deferred object failed, not waiting for all completed. This need more test thought – A. Wolff Sep 23 '13 at 11:28
2

Return promise interface, exposed by each ajax request, from your functions and use $.when() jquery method:

func1 ()
{
    return $.ajax(...,callback1)
}


func2 ()
{
    return $.ajax(...,callback2)
}


func3 ()
{
    return $.ajax(...,callback3)
}

$.when(func1(),func2(),func3()).done(/*callback*/);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

If you can't edit callbackN functions directly, make a wrapper, for instance:

func2 ()
{
    $.ajax(..., function() {
        //call your callback here
        callback2();

        //increase your counter here once it's done ...
    });
}

Is that what you wanted?

Tomalla
  • 567
  • 1
  • 6
  • 17
0

I think that you can use jQuery Deferred in this situation

Den Kison
  • 1,074
  • 2
  • 13
  • 28
0

One way is to synchronized all the Ajax calls and then you need to call your BigCallback

Otherwise you need to check what is the state(0- for request initiated, to 4) of the last Ajax then you can proceed according.