本机浏览器承诺一组查询元素

时间:2015-12-23 03:17:21

标签: javascript promise

在查询元素/节点时,有没有办法创建承诺/履行?这不起作用,因为我在el迭代器中得到undefined var completed = elements.every(function(el) { if (el.nodeType === 1)。另外,由于未定义,诺言不会拒绝。

没有jquery,请

var initialize = new Promise(function(resolve, reject) {
  rippleElement = document.getElementById('ripple-element');
  toolbar = document.querySelector('#main-toolbar');
  headerName = document.getElementById('name-title');
  panel = document.querySelector('paper-header-panel[main]');
  drawer = document.querySelector('paper-drawer-panel');
  mainPanelContent = document.getElementById('mainPanelContent');

  //elements is not routing list, routing list is elementList
  var elements = [rippleElement, toolbar, headerName, panel,
      drawer, mainPanelContent];

  var completed = elements.every(function(el) {
    if (el.nodeType === 1) {
      return true;
    } else {
      return false;
    }
  });

  if (completed) {
    resolve();
  } else {
    var errMsg = 'error in querying elements';
    reject(errMsg);
  }
});

1 个答案:

答案 0 :(得分:1)

正如@Arun所说,如果你不使用jQuery,也许你需要等待加载dom。



var initialize = new Promise(function(resolve, reject){

    function loaded(){
      
      var rippleElement = document.getElementById('ripple-element'),
          elements = [rippleElement],
          completed = _.every(elements, function(el) {
              if (el && el.nodeType === 1) return true;
              else return false;
          });
      
      
      if (completed) resolve();
      else reject('error in querying elements');
   
    }
  
    if (document.readystate === "complete"){
        window.addEventListener("load", loaded, false);
    } else {
        loaded();
    }

}).then(function(){
  // ok
}, function(err){
  // error
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<div id="ripple-element"></div>
<div id="result"></div>
&#13;
&#13;
&#13;