【问题标题】:Dojo fetch, how to wait on two simultaneous async fetches?Dojo fetch,如何等待两个同时进行的异步获取?
【发布时间】:2011-02-27 09:31:06
【问题描述】:

大家好,我不擅长处理异步设计模式,而且我在编写执行两次异步数据获取的脚本时遇到了问题。

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

知道 fetch 的 onComplete 字段以及如何使用它,但是我看到的最佳案例解决方案是在 onComplete 的 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()

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript asynchronous dojo fetch


    【解决方案1】:

    您可以为每个提取创建 dojo.Deferreds,然后使用 dojo.DeferredList 并将延迟添加到其中 - 请参阅here。此解决方案允许您利用将“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);
    

    【讨论】:

    • 我不明白的一点是使用 fetch 作为调用 Deferred 构造函数的值。这不是取消器吗?愿意解释一下它是如何工作的吗?
    • 你是对的 - 请参阅上面的更正代码。看起来 API 在 1.5 中发生了变化,所以您可能想查看所有基于 Promise 的新 API 和 dojo.when。
    【解决方案2】:
    // 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();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2022-07-06
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多