您最初的示例中的问题是
console.log
发生在
async
// 1. declaration happens
var locations;
// 3. this happens
$.getJSON(themeUri + '/resources/location.json', function(result){
locations = result;
console.log(locations); // it shows the right results.
});
// 2. console.log happens
console.log(locations); // undefined
所以这是有道理的
2.
未定义,因为回调尚未发生。
var locations;
function fillLocations(responseJSON) {
locations = responseJSON;
console.log(locations);
// Continue to next operationâ¦
}
$.getJSON( 'https://jsonplaceholder.typicode.com/todos/1', function(result){
fillLocations(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>