简体   繁体   中英

How do I return from synchronous callback?

First, have a look at this 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 is to "calculate" a value within the calculate function, and this value must be returned by the parent function.

Where should I place the return statement, and what should I return with it, in order to achieve this?

I tried 3 cases:

return #1 Here the output value is returned by the callback function, and not the parent function, so parent returns undefined.

return #2 Here the value of x is returned before executing the callback function, so parent returns 0.

return #3 + return #1 Here, I tried to return the output from the callback , and then (thinking that the return value of callback may somehow become the return value of the calculate itself), returned the calculatedValue , but again, parent returns undefined.

Please suggest a way, and plunk's over here

In this particular case, your callback is synchronous , which means you can return from it like so:

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

Then, you can return from the parent like so:

var parent = function() {    
  var calculatedValue = calculate(function(output) {
    return output; // tells the callback to do nothing with the output, just return it.
  });

  return calculatedValue; // return from parent
}

Note that if calculate is an asynchronous function, this approach won't work. Have a look at How do I return the response from an asynchronous call? for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM