1

嘿伙计们,我不擅长处理异步设计模式,而且我在编写一个执行两个异步数据获取的脚本时遇到了问题。

我使用 Dojo.data.api.Read.Fetch() 从单独的数据库进行两次 fetch() 调用。结果异步返回。但是,我必须交叉引用结果,所以我希望我的脚本在两个异步提取完成后继续。我不知道该怎么做,这就是问题所在。

我知道 fetch 的onComplete字段以及如何使用它,但我看到的最佳案例解决方案是在第一次 fetch 的 onComplete 中调用第二次 fetch 我想同时进行这些提取。有没有办法做到这一点?

这是我的程序的当前结构,用于说明目的:

this.dict1.fetch({query:"blahblahblah", onComplete: function(items) { something here? }});
this.dict2.fetch({query:"blahblahbleh", onComplete: function(items) { or maybe something here? }});
this.orMaybeDoSomethingAfterBothFetches()

任何帮助将不胜感激!

4

2 回答 2

2

您可以为每个提取创建 dojo.Deferreds,然后使用 dojo.DeferredList 并将延迟添加到其中 - 请参见此处。此解决方案允许您利用将“n”个函数添加到要调用的函数列表的优势。它还利用了 dojo.Deferred 的所有回调和 errBack 功能。

var fetch1 = new dojo.Deferred();
fetch1.addCallback(this.dict1.fetch...);
var fetch2 = new dojo.Deferred();
fetch2.addCallback(this.dict2.fetch...);

var allFuncs = new dojo.DeferredList([fetch1, fetch2]);
var doStuffWhenAllFuncsReturn = function() {...};
allFuncs.addCallback(doStuffWhenAllFuncsReturn);
于 2010-06-07T11:02:08.357 回答
1
// this is a variation of a function I have answered quite a few similar questions on SO with
function collected(count, fn){
    var loaded = 0;
    var collectedItems = [];
    return function(items){
        collectedItems = collectedItems.concat(items);
        if (++loaded === count){
             fn(collectedItems);
        } 
    }
}

var collectedFn = collected(2, function(items){
    //do stuff
});


this.dict1.fetch({query:"blahblahblah", onComplete: collectedFn);
this.dict2.fetch({query:"blahblahbleh", onComplete: collectedFn);

另一种解决方案是

var store = {
    exec: function(){
        if (this.items1 && this.items2) {
            // do stuff with this.items1 and this.items2
        }
    }
};

this.dict1.fetch({query:"blahblahblah", onComplete: function(items) {
    store.items1 = items;
    store.exec();
});
this.dict2.fetch({query:"blahblahbleh", onComplete: function(items) {
    store.items2 = items;
    store.exec();
});
于 2010-06-03T15:59:39.813 回答