Confusion with timings and JSON..Please help!

What I’m trying to do sounds simple. I want to load various chunks of data into javascript via json and then use it in other functions (such as jquery autocomplete).
I just can’t figure out how to delay the ‘other functions’ until the data is loaded.

townarray = getTownArray();
function getTownArray() {
	var myarray = [];
	var url = "ajaxjson.php?gettownlist=1"; // get town data
	$.getJSON(url,function(data) {
		$.each(data, function(key,value) {

The alert shows townarray is empty.
If I wrap the alert in a window.setTimeout, it is fine.

I’ve been going round in circles trying to delay the alert until the townarray is filled in. I’ve tried adding a callback to getTownArray, but it just wouldn’t wait for the array to be filled in - is that the way to go?
Can anyone help please?

Ajax requests by default run asynchronously which means the code does wait for the Ajax request to complete, to get around this we can simply use jQuery’s ajax method instead which has a setting to disable asynchronous connections and make them synchronous which means the code will only execute once the Ajax request is complete. See the below example:

function getTownArray() {
    var myarray = [];
        async    : false,
        dataType : 'json',
        url      : 'ajaxjson.php?gettownlist=1'
    }).success(function(data) {
        $.each(data, function(k, v) {
    return myarray;

Perfect, thank you!