如何传递已解决的值

时间:2017-12-10 06:19:37

标签: javascript promise

这个Promise使用了什么问题?

const count_elems = function(c){
  const elems = c.getElementsByTagName('p');
  console.log(elems.length);
};

const handler = function(){
    return new Promise(function (resolve, reject) {
     const cont = document.getElementById('cont');
     const p = document.createElement('p');
     for (let i=100000; i--;){
        cont.appendChild(p.cloneNode());
     }
     return resolve(cont);
  })
}

const test = function(){
  handler()
    .then(count_elems(c))
    .catch(function(e){console.log(e)});
};

document.getElementById('but')
  .addEventListener('click', test);
 <div id="cont"></div>
  <button id="but">click me</button>

2 个答案:

答案 0 :(得分:2)

获取Writer = animation.writers['ffmpeg']函数中的c,然后转到then函数。同时删除count_elems之前的return,您也不需要。{/ p>

resolve或仅.then(c => count_elems(c))没有函数调用。

&#13;
&#13;
.then(count_elems)
&#13;
const count_elems = function(c){
   const elems = c.getElementsByTagName('p');
   console.log(elems.length);
};

const handler = function() {

   return new Promise(function (resolve, reject) {
      const cont = document.getElementById('cont');
      const p = document.createElement('p');
      
      for (let i=100000; i--;){
         cont.appendChild(p.cloneNode());
      }
     
      resolve(cont);
  });
  
}

const test = function() {
   handler().then(c => count_elems(c))
            .catch(e => console.log(e));
};

document.getElementById('but')
        .addEventListener('click', test);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

.then(count_elems(c))应为.then(count_elems)