我在Google搜索jQuery Deferred and Promise for sequential execution of synchronous and asynchronous funcitons上找到了這個腳本。
這可能會解決我的問題,執行腳本sequient順序。但是我用then()函數的問題是我無法知道我可以調用這個函數多少次。我可以調用函數a()3次,下次我可以調用它20次,等等。所以,這對於then()不起作用。那麼()函數不允許數組堆棧。那麼,你們爲了使這個概念有效而做些什麼呢?
fucntion a(counter)
{
$deferred = $.Deferred();
//Run some scripts here...
alert(counter);
$deferred.resolve();
return $deferred;
}
function Test()
{
var d = $.Deferred(),
p=d.promise();
p.then(a(0)).then(a(1)).then(a(2));
d.resolve();
return d;
}
Test().done(function(){ alert('done'); }).fail(function() { alert('fail'); });
您正在將'a(N)'返回的'$ deferred'傳遞給'.then()'。相反,您需要傳遞迴調函數,例如'。然後(一)'。 – Bergi 2014-09-03 18:15:01
我不確定當你提到多次調用Test()時你的意思是什麼?這有什麼問題,當你這樣做時你會發生什麼? 「*允許數組堆棧*」是什麼意思? – Bergi 2014-09-03 18:16:28
我更新了問題,我的意思是一個(),而不是測試()... – fletchsod 2014-09-03 18:17:54