Search code examples
node.jses6-promisesynchronous

Correct way to call function synchronously


Let me start of by saying I know about async/await but I dont really want to include babel, it seems like to much trouble and I dont have any problem sticking with the promises. So what I am trying to do is pretty straightforward, basically achieve 'synchronous' flow in my function.

The code below gives me an unhandled exception. I'd like to hear any ideas why is that as well, if possible, whether I am on the right track here. If you have any questions please go ahead and ask.

function A()
{
    //...
    result = B();
    Promise.all(result).then(function(result){
        //after finishing B continue
    });
}

function B()
{
    //..
    C();
    return number;
}

function C()
{
    var data1;
    var data2;
    //..
    calling_DB = DB_get(..., function(result){ data1 = ..;});//callback cause I ma fetching data from DB
    Promise.all(data1).then(function(data1){
        calling_DB2 = DB_get(..., function(result){ data2 = ..;});
        Promise.all(data2).then(function(data2){
            //...
        });
    });
}

Solution

  • You can follow the below approach for calling those functions in the chain

    function A()
    {
        return B()
            .then(function(_merged_db_get_results)
            {
                //after finishing B continue
    
                console.dir(_merged_db_get_results);
    
                return true;
            })
            .catch(function(error)
            {
                console.dir(error);
                return false;
            });
    }
    
    function B()
    {
        return C()
            // Can be removed : START
            .then(function(_merged_db_get_results)
            {
                return _merged_db_get_results;
            });
            // Can be removed : END
    }
    
    function C()
    {
        var db_1_res;
    
        return Promise.resolve(true)
            .then(function(_above_true)
            {
                return DB_get(condition);
            })
            .then(function(_db_get_results_1)
            {
                db_1_res = _db_get_results_1;
    
                return DB_get(condition);
            })
            .then(function(_db_get_results_2)
            {
                return [db_1_res, _db_get_results_2];
            });
    }