Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  117] [ 7]  / answers: 1 / hits: 20856  / 9 Years ago, tue, october 6, 2015, 12:00:00

I just started working on node.js and getting to know its concepts, I am having a little trouble understanding callbacks,what I am trying to do is call function getUserBranch() in the function getOffers().



I read that because of node.js async nature its better to use a callback function to get the desired data once the complete execution is done.



Now I am having trouble retrieving the value that getUserBranch is returning,I have no proper idea how to do it, well the callback function has the value but how do I get the value from there?



file2.js



var getUserBranch = function(email,callback) {


client.execute('SELECT * from branch WHERE email=?', [ email ], function(
err, data, fields) {
if (err)

console.log(error);
else
console.log('The solution is in branch: n', data);
res = data.rows[0];
return callback(res);
});

}


file1.js



var getOffers = function (email) {

var branchObj = require('./file2.js');
var branchList = branchObj.getUserBranch(email,getList));
return branchList;
};

var getList = function(res){
var results=res;
return results;
}

More From » node.js

 Answers
1

In async call work with callback function in the stack. Look this:



var getUserBranch = function(email,callback) {
client.execute('SELECT * from branch WHERE email=?', [ email ], function(err, data, fields) {
if (err)
console.log(error);
else{
console.log('The solution is in branch: n', data);
/* This data stack 3 */
callback(data.rows[0];);
}
});
};

var getOffers = function (email, callback) {
var branchObj = require('./file2.js');
branchObj.getUserBranch(email, function(data){
/* This data stack 2 */
callback(data);
});
};

function anyFunction(){
getOffers([email protected], function(data){
/* This data stack 1 */
console.log(data);
});
}

[#64819] Saturday, October 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billie

Total Points: 101
Total Questions: 114
Total Answers: 98

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;