bluebird
bluebird copied to clipboard
Proposal : Bluebird.retry(), Bluebird.while(), Bluebird.or()
When working in bluebird, i find those 3 extensions very usefull. I am the only one? Is it worth it I to take some time to clean them to match Bluebird convention, add tests and make a PR to add them in bluebird?
import Bluebird from 'bluebird';
// Retry a function N times, with a delay in case of fail
Bluebird.retry = function(fn, nbRetry, delayBetween) {
return Bluebird.try(() => {
return fn();
}).catch((err) => {
if (nbRetry == 0) {
throw err;
}
return Bluebird.delay(delayBetween).then(() => {
return Bluebird.retry(fn, --nbRetry, delayBetween);
});
});
};
// A async version of a while() in bluebird
Bluebird.while = function(condition, action) {
const resolver = Bluebird.defer();
const loop = function() {
if (!condition()) return resolver.resolve();
return Promise.cast(action())
.then(loop)
.catch((err) => {resolver.reject(err)});
};
process.nextTick(loop);
return resolver.promise;
};
// or() implementation in Bluebird.
// Allowing for exemple
// this.getFromCache()
// .or(() => this.getFromDb())
// .or(() => this.getFromFlyingBird())
// .or(() => this.getEmptyState())
// .then((result) => this.displayResult());
Bluebird.prototype.or = function(fn) {
return this.then((result) => {
if (result) {
return result;
}
return fn();
})
};