Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from nested callback instead of the parent function

I have a parent function which has multiple callbacks and need to pass the result of the innermost callback to the function which calls this "parent" function. As NodeJS is asynchronous, my parent function obviously always returns before the callbacks are executed.

How can I make my callbacks return to the caller?

Code example that I am using right now -

var addNewUser = function(hash,name,number,time,syncTime){

// check here if the user exists or not by querying the phone number first
connection.query('SELECT user_id FROM users WHERE user_phone_number ="' +number+'"',function(err,rows,fields){

    if(rows[0]) return false;

    connection.query('INSERT INTO users (authorization_hash,user_name,user_phone_number,user_local_time,is_active,last_synced) VALUES ("'+hash+'","'+name+'","' + number+'","' +time+'","1","'+syncTime+'")',function(err,rows,fields){
    if(err) throw err;

    return true;    
        });

});
}

I Want to be able to return this callback return to the caller function.

like image 315
VaibhavAggarwal Avatar asked Apr 01 '26 17:04

VaibhavAggarwal


1 Answers

Have addNewUser accept a callback as its last argument and have the innermost function call the callback with the value.

Alternatively, you could look into having addNewUser return a promise. RSVP or Q are implementations of the Promises/A :

function addNewUser(hash,name,number,time,syncTime) {
    var deferred = Q.defer();
    connection.query("SELECT ...", function(err, rows, fields) {
        if(err) { deferred.reject(err); }
        if(rows[0]) { deferred.reject("some reason"); }
        connection.query("INSERT INTO ...", function(err, rows, fields) {
            if(err) { deferred.reject(err); }
            deferred.resolve(rows[0]); // Whatever addNewUser would return normally
        });
    });

    return deferred.promise;
}

Then the caller would use it like this:

addNewUser(...).then(function(newUserAdded) {
    // Do something with newUserAdded here
}, function(err) {
    // Do something with the error here
});
like image 170
Cedric Han Avatar answered Apr 03 '26 10:04

Cedric Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!