Instantly share code, notes, and snippets.
Last activeJuly 11, 2025 09:58
Save softwaredoug/9044640 to your computer and use it in GitHub Desktop.
Simple Javascript Promise Implementation (see this blog post:http://www.opensourceconnections.com/2014/02/16/a-simple-promise-implementation-in-about-20-lines-of-javascript/)
This file contains hidden or 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
| varPromise=function(wrappedFn,wrappedThis){ | |
| this.then=function(wrappedFn,wrappedThis){ | |
| this.next=newPromise(wrappedFn,wrappedThis); | |
| returnthis.next; | |
| }; | |
| this.run=function(){ | |
| wrappedFn.promise=this; | |
| wrappedFn.apply(wrappedThis); | |
| }; | |
| this.complete=function(){ | |
| if(this.next){ | |
| this.next.run(); | |
| } | |
| }; | |
| }; | |
| Promise.create=function(func){ | |
| if(func.hasOwnProperty('promise')){ | |
| returnfunc.promise; | |
| }else{ | |
| returnnewPromise(); | |
| } | |
| }; |
peter-moon commentedJul 22, 2015
sample usage
var foo = function() {
var promise = Promise.create(foo)
async.wait(function() {
promise.complete();
});
return promise;
}
dopatraman commentedAug 19, 2015
Doesnt work. Can you please provide a full example?
foo = new Promise(function() {return [1,2,3,4];});foo()TypeError: object is not a functionAlso doesnt work:
foo.then(function(i) {return i}).complete()Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment