我对 $.Deferred
的经验非常有限,到目前为止,代码看起来很乱。
应该返回 promise 的函数是用在 ajax 请求后收到的 HTML 更新 DOM。
它是这样使用的:
this._refreshWorkspace(response.html).then(function(){
// do things after DOM update finished
});
函数代码如下:
_refreshWorkspace: function(htmlBlocks){
var dfd = $.Deferred();
if('editor' in htmlBlocks){
app.destroy(this.editor).then((function(){
this.editor.empty().append(htmlBlocks.editor);
}).bind(this)).then((function(){
app.refresh(this.editor);
}).bind(this));
}
if('listPanels' in htmlBlocks){
app.destroy(this.list).then((function(){
this.list.empty().append(htmlBlocks.listPanels);
}).bind(this)).then((function(){
app.refresh(this.list);
// other unrelated code here
dfd.resolve();
}).bind(this));
}
if('listNav' in htmlBlocks){
// similar code block
}
return dfd;
},
它似乎有效,但前提是提供了“listPanels”htmlBlock。
我希望 dfd
在所有刷新调用之后被解析一次,或者如果可能的话更好 - 在所有刷新调用都被解析之后。关于如何实现这一目标的任何想法?
最佳答案
将循环中的所有 promise 放入一个数组中,然后使用 $.when
.可悲的是,将 $.when
与数组一起使用是丑陋的:
return $.when.apply($, theArray);
...因为 $.when
旨在接受离散参数而不是数组。
像这样:
_refreshWorkspace: function(htmlBlocks){
var promises = [];
if('editor' in htmlBlocks){
promises.push(
app.destroy(this.editor).then((function(){
this.editor.empty().append(htmlBlocks.editor);
}).bind(this)).then((function(){
app.refresh(this.editor);
}).bind(this))
);
}
if('listPanels' in htmlBlocks){
promises.push(
app.destroy(this.list).then((function(){
this.list.empty().append(htmlBlocks.listPanels);
}).bind(this)).then((function(){
app.refresh(this.list);
}).bind(this))
);
}
if('listNav' in htmlBlocks){
// similar code block
}
return $.when.apply($, promises);
},
这是一个使用随机 Deferred
s 的实例:
function doSomething() {
var promises = [];
var d1, d2, d3;
d1 = new $.Deferred();
promises.push(d1.promise());
setTimeout(function() {
snippet.log("Resolving d1");
d1.resolve(1);
}, Math.floor(Math.random() * 1000));
d2 = new $.Deferred();
promises.push(d2.promise());
setTimeout(function() {
snippet.log("Resolving d2");
d2.resolve(2);
}, Math.floor(Math.random() * 1000));
d3 = new $.Deferred();
promises.push(d3.promise());
setTimeout(function() {
snippet.log("Resolving d3");
d3.resolve(3);
}, Math.floor(Math.random() * 1000));
return $.when.apply($, promises);
}
// Use it
doSomething().then(function() {
snippet.log("All resolved");
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 在解析其他多个延迟对象后解析延迟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32106379/