Skip to content Skip to sidebar Skip to footer

How To Send A Return Form A Callback Function To The Main Function

I have this fiddle http://jsfiddle.net/jdsans/38GFS/ which I was trying to workout but I could not send return for the callback function to the main function. The callback function

Solution 1:

Looks like you're trying to have an asynchronous callback return a value (to a "synchronous" function call). That is like trying to captain a boat on dry land. The paradigms don't fit.

The concept of "return a value" only exists in a synchronous model. Where one function calls another, and values can be manipulated and returned. But your value that you want returned exists in a function callback. Which means that your entire execution thread will execute before the callback function, including the part where you save the returned value.

You need to think asynchronously. Don't return values, use them to call other functions that perform the necessary work.

I'll try and illustrate. Let's say I have code:

  1. Do something
  2. Call async function with a callback that returns a value
  3. Use the return value to print on the screen

The idea of async is that 1-3 execute before the callback is called. That's why it's called a callback!! So 3 will execute before we have the value. That doesn't make sense. Instead you need to change your code to execute:

  1. Do something
  2. Call asynch function with callback that uses a value and performs 3 from above.

Post a Comment for "How To Send A Return Form A Callback Function To The Main Function"