Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call callback only when all functions done

I'm new to this asynchronous stuff. I learned how to use call back, but now I need to use two functions (Asynchronously) and only after they will finish I want to call my callback:

function bigFunction(data, callback) {
    //only after they will finish ||
    func1(); //  <================||
    func2(); //  <================||
    //call callback
    callback();
}

Real code:

function getStarsStatus(star, callback) {

    require('./Bezeq').GetStarStatus(star, function(status) {
        statuses['Bezeq'] = status;
    });

    require('./Hot').GetStarStatus(star, function(status){
    statuses['Hot'] = status[0][0]['סטטוס'];
    });

}

Probably there is a very simple solution that I just don't know.

like image 739
Erel Nahum Avatar asked Jan 24 '26 10:01

Erel Nahum


1 Answers

This is easiest to do with Promises and Promise.all, but if your asynchronous functions don't return Promises and you don't want to Promisify them, you can also use a counter and call your callback when your counter reaches the number you expect:

function getStarsStatus(star, callback) {

    const numStatusesTotal = 2;
    let numStatusesFetched = 0;

    require('./Bezeq').GetStarStatus(star, function(status) {
        statuses['Bezeq'] = status;
        if ( ++numStatusesFetched === numStatusesTotal )
          callback( statuses );
    });

    require('./Hot').GetStarStatus(star, function(status){
        statuses['Hot'] = status[0][0]['סטטוס'];
        if ( ++numStatusesFetched === numStatusesTotal )
          callback( statuses );
    });

}
like image 187
Paul Avatar answered Jan 26 '26 23:01

Paul