Make AJAX “get” function synchronous / how to get

2019-02-16 09:42发布

问题:

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?

回答1:

The real answer is NO, but you can use this:

function useXYZ(){
    alert(xyz);
}

xyz = null        

$.get('http://www.someurl.com/123=json', function(data) {
   xyz = data.positions[0].latitude;
   useXYZ();
});


回答2:

get is a shortcut. You can do the same, but synchronous, using:

var xyz = null


$.ajax({ url: 'http://www.someurl.com/123=json', 
         async: false,
         dataType: 'json',
         success: function(data) {
              xyz = data.positions[0].latitude;
            }
        });


alert(xyz);

You'll have to declare the xyz variable before the ajax call, though.



回答3:

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

var x = someSyncFunction(a, b, c);
//do something with x
console.log(x);

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.

someAsyncFunction(a, b, c, function(x){
    //do something with x;
    console.log(x);
});

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)

var getXyz = function(onResult){ //async functions that return do so via callbacks
                                 //you can also another callback for errors (kind of analogous to throw)
    $.get('http://www.someurl.com/123=json', function(data) {
       var xyz = data.positions[0].latitude;
        onResult(xyz); //instead of writing "return xyz", we pass x to the callback explicitely.
    });
};

getXyz(function(xyz){ //this would look like "var xyz = getXyz();" if it were sync code instead.
    console.log('got xyz');
});

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)