javascript Node.js 获取函数的返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32976880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js get the return value of a function
提问by marilyn
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().
我刚刚开始研究 node.js 并开始了解它的概念,我在理解回调时遇到了一些麻烦,我想要做的是在函数getOffers()中调用函数getUserBranch()。
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.
我读到,因为 node.js 异步性质,一旦完成执行,最好使用回调函数来获取所需的数据。
Now I am having trouble retrieving the value that getUserBranchis 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?
现在我在检索getUserBranch返回的值时遇到问题,我不知道该怎么做,回调函数有值,但我如何从那里获取值?
file2.js
文件2.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
文件1.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;
}
回答by Emir Marques
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);
});
}