如何通过回调函数返回值 [英] How to get returned a value by a callback function

查看:141
本文介绍了如何通过回调函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

function save_current_side(current_side) {
    var result;
    var final = a.b({
        callback: function (a) {
            console.log(a); // its working fine here 
            return a;
        }
    });
}

其中b是同步函数。
我在代码中的任何地方调用上述函数

where b is the synchronous function. I am calling the above function anywhere in the code

var saved =  save_current_side(current_side);

保存的变量未定义。如何通过回调函数返回值

The variable saved is undefined. How to get returned valued by callback function

推荐答案

如果 b 是synchronoys方法,您只需将值存储在变量中,以便您可以从 save_current_side 函数而不是从回调函数返回它:

If b is a synchronoys method, you simply store the value in a variable, so that you can return it from the save_current_side function instead of from the callback function:

function save_current_side(current_side) {
  var result;
  a.b({
    callback: function (a) {
      result = a;
    }
  });
  return result;
}

如果 b 是一个异步方法,你不能从函数返回值,因为它在你退出函数时还不存在。使用回调:

If b is 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:

function save_current_side(current_side, callback) {
  a.b({
    callback: function (a) {
      callback(a);
    }
  });
}

save_current_side(current_side, function(a){
  console.log(a);
});

这篇关于如何通过回调函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆