Skip to content

Commit 7a5e11c

Browse files
committed
Implemented promiseFactory option, to allow usage of different promise libraries
1 parent 71ec0d2 commit 7a5e11c

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

index.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,33 @@ var DEFAULTS = {
1717
maxAttempts: 5, // try 5 times
1818
retryDelay: 5000, // wait for 5s before trying again
1919
fullResponse: true, // resolve promise with the full response object
20+
promiseFactory: defaultPromiseFactory // Function to use a different promise implementation library
2021
};
2122

23+
// Default promise factory wich use bluebird
24+
function defaultPromiseFactory(resolver) {
25+
return new Promise(resolver);
26+
}
27+
28+
/**
29+
* It calls the promiseFactory function passing it the resolver for the promise
30+
*
31+
* @param {Object} requestInstance - The Request Retry instance
32+
* @param {Function} promiseFactoryFn - The Request Retry instance
33+
* @return {Object} - The promise instance
34+
*/
35+
function makePromise(requestInstance, promiseFactoryFn) {
36+
37+
// Resolver function wich assigns the promise (resolve, reject) functions
38+
// to the requestInstance
39+
function resolver(resolve, reject) {
40+
this._resolve = resolve;
41+
this._reject = reject;
42+
}
43+
44+
return promiseFactoryFn(resolver.bind(requestInstance));
45+
}
46+
2247
function Request(options, f, retryConfig) {
2348
this.maxAttempts = retryConfig.maxAttempts;
2449
this.retryDelay = retryConfig.retryDelay;
@@ -44,10 +69,7 @@ function Request(options, f, retryConfig) {
4469

4570
// create the promise only when no callback was provided
4671
if (!this._callback) {
47-
this._promise = new Promise(function (resolve, reject) {
48-
this._resolve = resolve;
49-
this._reject = reject;
50-
}.bind(this));
72+
this._promise = makePromise(this, retryConfig.promiseFactory);
5173
}
5274

5375
this.reply = function requestRetryReply(err, response, body) {
@@ -100,7 +122,7 @@ Request.prototype.abort = function () {
100122
});
101123

102124
// expose promise methods
103-
['then', 'catch', 'finally'].forEach(function (promiseMethod) {
125+
['then', 'catch', 'finally', 'fail', 'done'].forEach(function (promiseMethod) {
104126
Request.prototype[promiseMethod] = function exposedPromiseMethod () {
105127
if (this._callback) {
106128
throw new Error('A callback was provided but waiting a promise, use only one pattern');

0 commit comments

Comments
 (0)