在面向對象的語言背景下,我試圖學習一些jquery,並圍繞異步調用進行打包。我的意圖是創建一個JavaScript對象來包含異步API調用的結果,並且能夠詢問所述對象是否已完成加載。
我一直在嘗試使用jQuery的Deferred's來完成它,並且我沒有任何問題需要使用片段來處理文檔示例,但它不會按照我期望的順序執行,類。
如何使用$ .Deferred作爲成員變量創建javascript對象?
(在我的連接代碼超時是模仿API調用延遲)
<!DOCTYPE html>
<html>
<body>
<script src="jquery-3.1.1.js"></script>
<script>
//top level
var isdone = false;
var def = $.Deferred();
$.when(def).done(function() {
var msg = "checking topLevel isdone " + isdone;
console.log(msg);
$("body").append("<p>" + msg + "</p>");
})
var delayedCall = function() {
setTimeout(function() {
//resolve after 5 seconds
isdone = true;
def.resolve();
}, 1000);
}
delayedCall();
//inside function
function DelayedObject()
{
this.defThis = $.Deferred();
var defVar = $.Deferred();
this.delayedObjCall = function()
{
setTimeout(function()
{
//resolve after 5 seconds
isdone = true;
this.def.resolve();
}, 1000);
}
this.delayedObjCall();
this.getStatusThis = function()
{
return this.def;
}
this.getStatusVar = function()
{
return this.def;
}
}
delObj = new DelayedObject();
$.when(delObj.getStatusThis()).done(function() {
var msg = "checking delObj (this) isdone " + isdone;
console.log(msg)
$("body").append("<p>" + msg + "</p>");
});
$.when(delObj.getStatusVar()).done(function() {
var msg = "checking delObj (var) isdone " + isdone;
$("body").append("<p>" + msg + "</p>");
console.log(msg)
});
$(window).on("load", function()
{
var msg = "<p>" + " Page loaded " + "</p>";
$("body").append(msg);
console.log(msg);
});
</script>
</body>
</html>
結果
checking delObj (this) isdone false
checking delObj (var) isdone false
Page loaded
checking topLevel isdone true
'this.def','this.defThis','defVar' ???你想*一個*延期。 – Bergi
我知道,我在這裏包括多個以更好地說明我的問題。可能在代碼註釋中提到過雖然 – Schaki