Javascript 如何通过回调函数获取返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14182778/
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
How to get returned a value by a callback function
提问by Muhammad Usman
Here is my code
这是我的代码
function save_current_side(current_side) {
var result;
var final = a.b({
callback: function (a) {
console.log(a); // its working fine here
return a;
}
});
}
where b is the synchronous function. I am calling the above function anywhere in the code
其中 b 是同步函数。我在代码中的任何地方调用上述函数
var saved = save_current_side(current_side);
The variable saved is undefined. How to get returned valued by callback function
保存的变量未定义。如何通过回调函数获取返回值
回答by Guffa
If bis a synchronoys method, you simply store the value in a variable, so that you can return it from the save_current_sidefunction instead of from the callback function:
如果b是同步方法,您只需将值存储在变量中,以便您可以从save_current_side函数而不是从回调函数返回它:
function save_current_side(current_side) {
var result;
a.b({
callback: function (a) {
result = a;
}
});
return result;
}
If bis an asynchronous method, you can't return the value from the function, as it doesn't exist yet when you exit the function. Use a callback:
如果b是异步方法,则无法从函数返回值,因为退出函数时该值尚不存在。使用回调:
function save_current_side(current_side, callback) {
a.b({
callback: function (a) {
callback(a);
}
});
}
save_current_side(current_side, function(a){
console.log(a);
});
回答by nekman
You need to submit the callback function. Example:
您需要提交回调函数。例子:
function save_current_side(current_side, callback) {
a.b({
callback: callback
});
}
save_current_side(current_side, function() {
console.log('saved'):
});
回答by Tripathi29
You just have to pass the callback as argument in the function as given below
您只需要在函数中将回调作为参数传递,如下所示
function save_current_side(current_side,callback) {
var result;
var final = a.b(function(){
callback(a);
});
}
This is how you can call it anywhere in the code
这是您可以在代码中的任何位置调用它的方式
var saved;
save_current_side(current_side,function(saved){
console.log(saved);
});

