17

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

Muhammad Usman
  • 10,426
  • 22
  • 72
  • 107

4 Answers4

28

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);
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 4
    Dear Guffa How can i use the a value out of the " save_current_side " after callback?? – Kostantinos Ibra Feb 26 '16 at 23:14
  • @KostantinosIbra: You can't, as the function returns before the callback. You can return whatever you like from the function and use that as normal, but as that happens before the callback you don't have access to the result from the asynchronous call at that time. – Guffa Jun 03 '16 at 10:42
4

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);
});
clemens
  • 16,716
  • 11
  • 50
  • 65
Abhishek Tripathi
  • 1,570
  • 3
  • 20
  • 32
3

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'):
});
nekman
  • 1,919
  • 2
  • 15
  • 26
2

Use Promise. Once data is read/fetched resolve it. Later, at call point use then(data) with resolved value inside. My project example:

function getImage(imagename) {
    return new Promise((resolve, reject) => {
        fs.readFile(`./uploads/${imagename}`, 'utf8', function(err, data){
            if(err) {
                reject(null);
                throw err;
            }
            resolve(data);
        });
    });
}

io.on('connection', async (socket) => {
        getImage(imagename).then(image => {
            console.log('Img contents: ' + image);
        });
        ....
    });
});
M22
  • 543
  • 5
  • 10