Created
May 4, 2015 07:37
-
-
Save humidair1999/b5fef4b9b8d357368315 to your computer and use it in GitHub Desktop.
Simple JS Deferred/Promise implementation
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
// 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