我刚刚开始研究node.js并了解它的概念,我在理解回调方面遇到了一些麻烦,我想做的是调用函数 getUserBranch() < / strong>在函数 getOffers() 。
我读到因为node.js异步性质,一旦完成执行,最好使用回调函数来获取所需的数据。
现在我无法检索 getUserBranch 返回的值,我不知道怎么做,回调函数有值但是怎么做我从那里得到了价值?
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;
}
答案 0 :(得分:3)
异步调用在堆栈中使用回调函数。看这个:
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("xx@xxx.com", function(data){
/* This data stack 1 */
console.log(data);
});
}