Vern
Vern

Reputation: 11

Detect asynchronous calls are finished, then trigger another function?

What is the best way to detect when all of my asynchronous calls are finished then trigger another function? I have three querys that are triggered by the user picking a topic. These querys run and their return values are then combined to be used in a new function. The problem is I need to know when they are all done then run the new function.

function queryHandler1() {
    // do something
    return result1;
}

function queryHandler2() {
    // do something
    return result2;
}

function queryHandler3() {
    // do something
    return result3;
}

function alldone(result1, result2, result3) {
     // do something
    return result4;
}

I have tried using jquery.when(), but it only runs the first time and when the user picks a new option it does not trigger alldone?

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

function queryHandler1() {
    // do something
    d1.resolve();
    return result1;
}

function queryHandler2() {
    // do something
    d2.resolve();
    return result2;
}

function queryHandler3() {
    // do something
    d3.resolve();
    return result3;
}

function alldone(result1, result2, result3) {
     // do something
    return result4;
}

// the top level $.when
$.when(d1, d2, d3).done(function() {
    alldone();
});

How do I reset the deferred or resolve so that all done is triggered again?

Thanks for the help!

Upvotes: 1

Views: 72

Answers (2)

Vern
Vern

Reputation: 11

I solved this issue with what I think is an inelegant solution, but it works.

function queryHandler1() {
    // do something
    alldone(); 
}

function queryHandler2() {
    // do something
    alldone();
}

function queryHandler3() {
    // do something
    alldone();
}
var numCalls = 0;
function alldone() {
     if (numCalls === 2) {
          // do something
          console.log("YES ALL DONE");
     } else {
          numCalls ++;
     }
}

Any improvements?

Thanks

Upvotes: 0

Samir Aleido
Samir Aleido

Reputation: 1046

You can use Async library

For your case you can use async.parallel or async.series depending on wether you want to run your tasks simultaneously or sequentially

To use the library in the browser https://www.jsdelivr.com/package/npm/async

Upvotes: 1

Related Questions