I'm experiencing a problem of $.get function. The url contains JSON
my code:
xyz = null
$.get('http://www.someurl.com/123=json', function(data) {
var xyz = data.positions[0].latitude;
});
alert(xyz);
//some more code using xyz variable
I know that xyz
will alert a null result because the $.get
is asynchronous.
So is there any way I can use the xyz
outside this get function?
The real answer is NO, but you can use this:
This is a common issue with Javascript. Javascript code must be written in continuation passing style. Its annoying but its something you can convert without thinking too much.
Basicaly, whenever we would have something like
We can convert it into async code by making all the code after the function returns into a continuation function and turning x from a variable into a parameter of the continuation callback.
You have to watch out that its very easy to write confusing code. A good trick to keep in mind is taht you can make your own functions also receive callbacks. This allows them to be used by different function (just like normal sync helper functions that return a value can be used by different functions)
The trick here is to change all return statements from the function into calls to the callback function. Think as if async function never returned and the only way to give a value back to someone is to pass that value to a callback.
You might ask why there isnt an easier way to do all of this. Well, there is not, unless you use another language instead of Javascript (or at least something that lets you write async code in synchronous style but automatically compiles down to regular Javascript)
get
is a shortcut. You can do the same, but synchronous, using:You'll have to declare the
xyz
variable before the ajax call, though.