Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 890
Muhammad Usman Avatar asked Jan 06 '13 13:01

Muhammad Usman


People also ask

Can callback function return a value?

When a callback function completes execution, it returns any return value that it might have to the DataBlade API, which invoked it.

How do you get the variable from a callback function?

You can pass the exec function a callback. When the exec function determines the username, you invoke the callback with the username. var child = exec(cmd, function(error, stdout, stderr, callback) { var username = stdout. replace('\r\n',''); callback( username ); });

How do I return a value from a callback function in TypeScript?

Use of Generic for Callback Type in TypeScript The callback will not return any value most of the time, so the typeTwo type is default set to void. But in case you want to return a value from a callback function, you could specify the typeTwo type.


1 Answers

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);
});
like image 135
Guffa Avatar answered Oct 23 '22 15:10

Guffa