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 contains end return value exactly what I want but its not returning back.
When I use the document.write() function to print the return value then I get the exact value printed that I want but as I said earlier it doesn't gets returned.
Please can anybody work with this fiddle to show me a working example. I have added more details in the fiddle as comments so that you don't have any problem understanding me.
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:
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: