您可以傳遞一個回調函數來assignContactCategoryToLocal()
這樣你可以繼續運行,只有當AJAX完成的代碼。事情是這樣的:
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
assignContactCategoryToLocal(category, myCallbackFunction);
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
}
了一個例子,你可以得到的類別一次,然後把它傳遞的功能,也許可以幫助理解它們是如何連接。
編輯: 要與該類別是null
解決這個問題,這裏是一個修訂版。
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
// Move the if statement here so it checks the condition earlier.
if (category === null) {
assignContactCategoryToLocal(category, myCallbackFunction);
} else {
myCallbackFunction(category);
}
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
你可以使用'Promise'並在'onFulfilled'處理 – Lucius
@LiYinKong執行代碼的其餘部分 - 如果你不希望你的代碼在IE工作。 – aroth
@aroth從jQuery 1.5開始,由'$ .ajax()'返回的jqXHR對象通過'done'和'fail'實現了Promise接口 – Lucius