Created
August 6, 2018 15:54
-
-
Save srhyne/f03e86eda73e4ca93658406e73f67a0e to your computer and use it in GitHub Desktop.
$.Deferred Alternative using Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Deferred( executor ){ | |
var self = this; | |
this._promise = new Promise(function(resolve, reject){ | |
self._resolver = resolve; | |
self._rejector = reject; | |
if( typeof executor === 'function' ){ | |
executor(resolve, rejector) | |
} | |
}); | |
} | |
Deferred.all = function(deferreds){ | |
var promises = deferreds.map(function(d){ | |
return d.promise(); | |
}); | |
return Promise.all(promises) | |
} | |
Object.assign(Deferred.prototype, { | |
promise : function(){ | |
return this._promise; | |
}, | |
//returns promise | |
then : function(cb){ | |
return this._promise.then(cb); | |
}, | |
//returns promise | |
catch : function(){ | |
return this._promise.catch(cb); | |
}, | |
finally : function(){ | |
return this._promise.finally(cb); | |
}, | |
//returns Deferred | |
done : function(cb){ | |
this._promise.then(cb); | |
return this; | |
}, | |
//returns Deferred | |
fail : function(cb){ | |
this._promise.catch(cb); | |
return this; | |
}, | |
resolve : function(value){ | |
this.resolved = true; | |
this._resolver(value); | |
return this; | |
}, | |
reject : function(){ | |
this._rejector(value) | |
return this; | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment