Javascript Promises: Chain same promise n times, then do something else
<p>I have a promise-returning function that does some async stuff, let's call it <code>functionToRepeat()</code>.</p>

<p>I am trying to write the function <code>repeatFunction(amount)</code> , so that it will start the promise, wait for completion, start it again, wait for completion, and so on a given amount of times. This <code>repeatFunction(amount)</code> should also be thenable, so that I can chain other stuff after it's been executed.</p>

<p>Here is my attempt:</p>

<pre><code>function functionToRepeat(){
  let action = new Promise(function(resolve,reject){
    setTimeout(function(){
      console.log("resolved!");
      resolve()}
    ,1000);
  })
  return action
}

function repeatFunction(amount) {
  if(amount==0){
    return Promise.resolve();
  }
  return functionToRepeat().then(function(){
    repeatFunction(amount-1);
  });
}

repeatFunction(5).then(function(){
 console.log("DONE!");
})
</code></pre>

<p>This successfully chains my promises (or so it seams, I get one "resolved!" per second in the console).
However the <code>.then()</code> I try to chain after my <code>repeatFunction(5)</code> happens after the 1st promise ends, not after all 5 have ended!</p>

<p>So in my console I get:</p>

<p>resolved!
DONE!
resolved!
resolved!
resolved!
resolved!</p>

<p>What am I doing wrong and what should I change?</p>