I have a promise-returning function that does some async stuff, let's call it functionToRepeat()
.
I am trying to write the function repeatFunction(amount)
, 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 repeatFunction(amount)
should also be thenable, so that I can chain other stuff after it's been executed.
Here is my attempt:
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!");
})
This successfully chains my promises (or so it seams, I get one "resolved!" per second in the console).
However the .then()
I try to chain after my repeatFunction(5)
happens after the 1st promise ends, not after all 5 have ended!
So in my console I get:
resolved! DONE! resolved! resolved! resolved! resolved!
What am I doing wrong and what should I change?