Skip to content

Instantly share code, notes, and snippets.

@humidair1999
Created May 4, 2015 07:37
Show Gist options
  • Save humidair1999/b5fef4b9b8d357368315 to your computer and use it in GitHub Desktop.
Save humidair1999/b5fef4b9b8d357368315 to your computer and use it in GitHub Desktop.
Simple JS Deferred/Promise implementation
// promise definition
var Promise = function() {
this.successCallbacks = [];
this.errorCallbacks = [];
};
Promise.prototype.then = function(successCallback, errorCallback) {
console.log('then()');
this.successCallbacks.push(successCallback);
if (errorCallback) {
this.errorCallbacks.push(errorCallback);
}
};
// defer definition
var Defer = function () {
this.promise = new Promise();
};
Defer.prototype.resolve = function(data) {
console.log('resolve()');
this.promise.successCallbacks.forEach(function(callback) {
window.setTimeout(function () {
console.log(callback);
callback(data);
}, 0);
});
};
Defer.prototype.reject = function(error) {
console.log('reject()');
this.promise.errorCallbacks.forEach(function(callback) {
window.setTimeout(function () {
console.log(callback);
callback(error);
}, 0);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment