在解析其他多个延迟对象后解析延迟对象

时间:2015-08-19 22:03:15

标签: javascript jquery jquery-deferred

我对$.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一次,如果可能的话,甚至更好 - 在解决所有刷新调用之后。关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:1)

将循环中的所有promises放入数组中,然后使用$.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>

答案 1 :(得分:1)

正如已经解释的那样,问题的简单答案是将个别承诺与$.when.apply(null, promiseArray)汇总。

但是,如果问题中的所有代码都代表了要应用于所有html块的处理,那么您可以更进一步。

jQuery.map()将对一个对象的ownProperties进行操作,因此可以利用它来迭代htmlBlocks,从而产生一个简洁,通用的主例程,并带有几个支持哈希值。

_refreshWorkspace: function(htmlBlocks) {
    var that = this; // avoids the need for .bind(this) in the promise chain and the methodsHash
    var propHash = {
        'editor': 'editor',
        'listPanels': 'list'
    };
    // All the "other unrelated code" is defined here
    var methodsHash = {
        'editor': null,
        'listPanels': function(key, obj) {
            ...
        },
        ...
    };
    //And the main routine is a concise $.map(htmlBlocks, ...) structure. 
    var promises = $.map(htmlBlocks, function(html, key) {
        var obj = that[propHash[key]];
        return app.destroy(obj).then(function() {
            obj.empty().append(html); //if empty() and append() are jQuery methods then this line is synchronous.
            return app.refresh(obj);// if app.destroy() is asynch and theanable, then it seems safe to assume that app.refresh() is also asynch and theanable. Therefore return the result here.
        }).then(function() {
            if(methodsHash[key]) {
                methodsHash[key](key, obj);
            }
        });
    });

    //Now aggregate `promises` into a single promise which resolves when all the promises resolve, or rejects when any of the promises rejects.
    return $.when.apply(null, promises);
},

现在,为了满足所有其他html块,只需向propHash添加一行,向methodsHash添加null或函数。提供主要程序是全面的,不需要修改。

恕我直言,这是一种更好的组织代码的方法。