I updated one of my websites to use JavaScript promises instead of callbacks. It was pretty straightforward, but got a little tricky for a recursive function. Below is how to do the conversion update:
Recursive callback function:
function doSomething(value) {
function callback(result) {
console.log(‘Done ‘ + result);
}
theRecursiveFunction(value, callback);
}
function theRecursiveFunction(value, next) {
if (value> 3) {
console.log(‘Try again ‘ + value);
theRecursiveFunction(value-1, next);
} else {
next(value);
}
}
doSomething(5);
Recursive function with promises:
function doSomething(value) {
theRecursiveFunction(value)
.then((result) => {
console.log(‘Done ‘ + result);
});
}
function theRecursiveFunction(value) {
return new Promise((resolve, reject) => {
if (value > 3) {
console.log(‘Try again ‘ + value);
theRecursiveFunction(value-1)
.then((result) => {
resolve(result);
});
} else {
resolve(value);
}
});
}
doSomething(5);
(paid links)
Leave a Reply
You must be logged in to post a comment.