Reputation: 98
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.
Upvotes: 3
Views: 4944
Reputation: 174
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
});
Upvotes: 1