0

what's wrong with this Promise using?

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>
shmnff
  • 647
  • 2
  • 15
  • 31
  • what issue you are facing? – programtreasures Dec 10 '17 at 06:23
  • There is no need for the promises, there is no asynchronous code anywhere. Are you expecting the promise to run on it's own thread? That is simply not the case though. Why JS uses promises is explained here: https://stackoverflow.com/a/47678417/1641941 – HMR Dec 10 '17 at 07:00

2 Answers2

2

Get the c in the then function and then pass into the count_elems function. Also remove the return before the resolve, you don't need that.

.then(c => count_elems(c)) or just .then(count_elems) without function call.

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>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

.then(count_elems(c)) should be .then(count_elems)

Ultimater
  • 4,647
  • 2
  • 29
  • 43