Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - How to get returned a value by a callback function

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

var saved =  save_current_side(current_side);

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...