lets say i have this async functuin:
function fooAsync(){
callSomeApi(some_args, callbackFunction(results){
return results; //i want to return the results here after the api call.
}
}
i’m looking for a way to assign the return value from the prev function to a var and continue with the code only when i have this value.
//some code here
var foo = fooAsync();
//some code here after getting back from the async function.
the problem is that foo will be undefined since javascript will return before the inner async api call will finish. I know i can use callbacks for that but i’m looking for a way to ‘lock’ the async function and resume back only when it got the result. That way i wont have to pass all the code after the async call as a callback.
to make things short – how can i return value from async ajax call (in my case i call google maps api) in a regular sync way?
Generally it’s a bad idea to make an ajax call synchronous. There is a property on the XMLHttpRequest object that you can set (jQuery allows you to do this easily) to make a synchronous ajax request. I’m not sure if the google maps API exposes this capability but you should check there first.
I know you said you don’t want to work with callbacks but aside from doing something like this:
there really isn’t any way to lock down the current execution context.
Also with the code you provided, that method would never return anything other than undefined. You are calling the api method (which executes asynchronously) and immediately returning control. The ‘return’ statement inside of the response handler of the api method call would only return inside of the anonymous function. So even if you were able to lock the thread until the results are back, you wouldn’t have them.
If, however, you are interested in going about this in the correct manner then you should use the deferred / promise model that jQuery provides.
Then you would change your calling code to be like this:
jQuery Deferred Object Documentation