admin管理员组文章数量:1356815
How can I get the value of var result
in this code?
I know this is a basic problem but I'm looking for the solution since 3 days. Can you give me any suggestion please?
function foo(myCallback){
}
function bar() {
var result = foo(function(){
var result = "hello";
return result;
});
}
var showResult = bar();
alert(showResult);
How can I get the value of var result
in this code?
I know this is a basic problem but I'm looking for the solution since 3 days. Can you give me any suggestion please?
function foo(myCallback){
}
function bar() {
var result = foo(function(){
var result = "hello";
return result;
});
}
var showResult = bar();
alert(showResult);
Share
Improve this question
edited Apr 4, 2016 at 11:23
Priya
1,3516 gold badges21 silver badges41 bronze badges
asked Apr 4, 2016 at 10:58
zm455zm455
4991 gold badge11 silver badges26 bronze badges
2
-
You can get it in the
callback
– Rayon Commented Apr 4, 2016 at 10:59 -
function foo(myCallback) { } function bar(cb) { foo(function() { var result = "hello"; cb(result); }); } bar(function(res) { alert(res); });
– Rayon Commented Apr 4, 2016 at 11:02
3 Answers
Reset to default 6You need to call the callback and return the value of it and inside your bar
function, you need to return the result as well
function foo(myCallback){
// return the value of the call myCallback()
return myCallback();
}
function bar(){
var result = foo(function(){
var result = "hello";
return result;
});
// return the result
return result;
}
var showResult = bar();
alert(showResult);
A bit simplified it could be
function foo(myCallback){
return myCallback();
}
function bar(){
return foo(function(){
return "hello";
});
}
var showResult = bar();
alert(showResult);
You are missing the return statements. It isn't clear what you want to return.
It works like this:
function foo(myCallback){
return myCallback();
}
function bar(){
var result = foo(function(){
var result = "hello";
return result;
});
return result;
}
var showResult = bar();
alert(showResult);
You are stuck using callbacks, but fortunately you can pass parameters in your callback functions:
// define your functions
function foo(myCallback){
myCallback();
}
function bar(callback){
var result = foo(function(){
var result = "hello";
callback(result);
});
}
// now run it
bar(function(showResult){
alert(showResult);
});
本文标签: callbackjavascript returning value from anonymous functionStack Overflow
版权声明:本文标题:callback - javascript: returning value from anonymous function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744069259a2585587.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论