As I said in my comment, to your question, you had an infinite loop since to call nonPromiseCallback
the result of tryUntilThree
was needed... and to get that, tryUntilThree
was called... and it was looping until memory was exhausted or the end of the universe, whichever came first.
You need to make two changes:
function nonPromiseCallback(x, resolve, reject){
if(x < 3){
reject(x+1) // the increment of x is moved to here.
}else{
resolve(x)
}
}
function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree); // Just pass the function, it will be called later
})
}
tryUntilThree(1)
.then(console.log);
If you can use async and await (new features since 2017) you could solve it like this (I moved the decision of maximum number of tries to the calling function) :
function nonPromiseCallback(x, resolve, reject){
if(x < 3){
reject(x+1)
}else{
resolve(x)
}
}
async function tryUntilThree(){
const maxAttempts = 3;
let attempt = 1;
do {
try {
// "await" waits for the prommise to resolve or reject.
// If it is rejected, an error will be thrown. That's why
// this part of the code is inside a try/catch-block.
const result = await new Promise( (resolve, reject) =>
nonPromiseCallback( attempt, resolve, reject )
);
return result; // Return the result from nonPromiseCallback
}
catch (error) {
// The nonPromiseCallback failed. Try again
attempt += 1;
}
} while ( attempt <= maxAttempts );
// Signal error after all retires.
throw Error(`Failure, even after ${maxAttempts} tries`);
}
tryUntilThree()
.then(console.log);