javascript - 如何传递解析值

标签 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>

最佳答案

then函数中获取c,然后传入count_elems函数。另外,请删除 resolve 之前的 return,您不需要这样做。

.then(c => count_elems(c)) 或仅 .then(count_elems) 而无需函数调用。

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);
<div id="cont"></div>
<button id="but">click me</button>

关于javascript - 如何传递解析值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47736433/

相关文章:

javascript - 无法获得与 Bluebird promisfy 一起使用的非 Node 回调库

javascript - 是否有另一种方法可以在 .map() 中添加 prop 并返回对象

javascript - $.when().done() 不工作

javascript - 有没有另一种方法可以在类 "tags"的范围内循环数组

javascript - 如何在 jQuery Mobile 中延迟页面转换,直到页面数据准备好?

ios - 如何使用 PromiseKit 在不同的 swift 类中链接 promise ?

node.js - Node JS后端中的错误处理

JavaScript 嵌套 Promise 范围和 AngularJS

javascript - ExtJS 从现有商店创建记录

javascript - 通过 Waterline (Sailsjs) 传递 bool 值?