初期化データを返すメソッドがあります。最初に sessionStorage をチェックします。そこにデータが見つからない場合は、サーバーを呼び出してデータを取得します。コードは次のとおりです。
function getInitializationData() {
// Check local storage (cache) prior to making a server call.
// Assume HTML 5 browser because this is an Intranet application.
if (!sessionStorage.getItem("initialData")) {
// The browser doesn't have the initialization data,
// so the client will call the server to get the data.
// Note: the initialization data is complex but
// HTML 5 storage only stores strings. Thus, the
// code has to convert into a string prior to storage.
$.ajax({
url: "../initialization.x",
type: "POST",
dataType: "json",
timeout: 10000,
error: handleError,
success: function(data) { sessionStorage.setItem("initialData", JSON.stringify(data)); }
});
}
// convert the string back to a complex object
return JSON.parse(sessionStorage.getItem("initialData"));
}
問題は、ほとんどの場合、メソッドが返された後に成功関数が実行されることです。getInitializationData メソッドの return ステートメントの前に成功関数を実行する必要があるように、サーバー呼び出しを同期させるにはどうすればよいですか?