javascript - How do I return from synchronous callback? -


first, have @ sample:

var calculate = function(callback) {   // calculating...   callback(5); }  var parent = function() {   var x = 0;    var calculatedvalue = calculate(function(output) {     return output; // return #1      x = output;   });    return x; // return #2    return calculatedvalue; // return #3 } 

my objective "calculate" value within calculate function, , value must returned parent function.

where should place return statement, , should return it, in order achieve this?

i tried 3 cases:

return #1 here output value returned callback function, , not parent function, parent returns undefined.

return #2 here value of x returned before executing callback function, parent returns 0.

return #3 + return #1 here, tried return output callback, , (thinking return value of callback may somehow become return value of calculate itself), returned calculatedvalue, again, parent returns undefined.

please suggest way, , plunk's on here

in particular case, callback synchronous, means can return so:

var calculate = function(callback) {   // calculating...   return callback(5); } 

then, can return parent so:

var parent = function() {       var calculatedvalue = calculate(function(output) {     return output; // tells callback nothing output, return it.   });    return calculatedvalue; // return parent } 

note if calculate asynchronous function, approach won't work. have @ how return response asynchronous call? that.


Comments