Last active
April 17, 2020 20:55
-
-
Save SimplGy/6921190 to your computer and use it in GitHub Desktop.
Sample Promise Implementation. Wrote in https://coderpad.io/626322
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 Implementation | |
Promise = function () { | |
this._stack = []; | |
this._isResolved = false; | |
} | |
Promise.prototype = { | |
success: function(callback){ | |
// Is the promise already resolved? | |
if(this._isResolved) { | |
callback( this._result ); | |
} else { | |
this._stack.push(callback); | |
} | |
}, | |
resolve: function(result){ | |
if(this._isResolved) { throw new Error('Promise Has Already Resolved'); } | |
this._result = result; | |
// Clear the promise stack | |
for (var i = 0; i < this._stack.length; i++) { | |
this._stack[i](result); | |
} | |
this._isResolved = true | |
} | |
} | |
// --------------------------------------------- "Assertions" | |
var foo = new Promise(); | |
var bar = new Promise(); | |
foo.resolve('hello'); | |
setTimeout(function(){ | |
bar.resolve('world'); | |
}, 500); | |
foo.success(function(result){ | |
console.log(result); | |
}); | |
bar.success(function(result){ | |
console.log(result); | |
}); | |
// => "hello" | |
// ... 500ms later ... | |
// => "world" | |
//A promise should only be able to be resolved once. Subsequent calls to resolve should error. | |
setTimeout(function(){ | |
bar.resolve('world again'); // Throws error | |
}, 750); | |
//A promise may have multiple success callbacks attatched. | |
setTimeout(function(){ | |
var baz = new Promise(); | |
baz.success(function(result){ console.log(result); }); | |
baz.success(function(result){ console.log(result.split('').reverse().join('')); }); | |
baz.resolve('Rainbow Bunny!'); | |
}, 1000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment