あなたの機能:
function(json) {
data2 = json;
}
は、その時点ではまだ定義されていない
console.log(data2); SelectedData = data2;
後
data2
を実行します。
(1) function prepData(){
(2) data2 = [];
(3) $.getJSON('http://localhost/data').done(function(json) {
(4) data2 =json;
(5) console.log(data2);
});
(6) console.log(data2);
(7) SelectedData= data2;
(8) return SelectedData;
};
実行順序:
1 -> 2 -> 3 -> 6 -> 7 -> 8 -> 4 -> 5
共通プラクティス - データの代わりに戻り約束:
function prepData(){
return $.getJSON('http://localhost/data');
}
// more code here
prepData().done(function(json){
console.log(json);
});
これらのより詳細なデモを見てみましょう。 ES5で
のjQuery:https://jsfiddle.net/DerekL/xtmy6po0/
function timeout(n){
// create promise
var defer = $.Deferred();
// resolve after n milliseconds
setTimeout(function(){
defer.resolve(n);
}, n);
// return new promise that apply custom text
return defer.then(function(v){
return "Resolved after " + (v/1000) + " seconds";
});
}
timeout(3000).then(function(message){
// will be executed after 3 seconds
alert(message);
});
等価ES7:それはあなたの次のコンソールステートメントに並列に実行されますので、https://jsfiddle.net/DerekL/8kLknbne/
async function timeout(n){
// create timer
let timer =() => new Promise(resolve => setTimeout(() => resolve(n), n));
// return message
return "Resolved after " + (await timer()/1000) + " seconds";
}
// call
timeout(3000).then(alert);
非同期コード(getJSONの呼び出しのような)は、コードが完了するまで実行を停止させません。これが非同期である理由です。 –