Last active
June 8, 2018 01:47
-
-
Save dobriai/7e3cb67b9aa25ee3250b822ffc4cab30 to your computer and use it in GitHub Desktop.
JS Promises - trivial impl.
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 Promise(fn) { | |
var state = 'pending'; | |
var value; | |
var deferred = null; | |
function resolve(newValue) { | |
if(newValue && typeof newValue.then === 'function') { | |
newValue.then(resolve); | |
return; | |
} | |
value = newValue; | |
state = 'resolved'; | |
if(deferred) { | |
handle(deferred); | |
} | |
} | |
function handle(handler) { | |
if(state === 'pending') { | |
deferred = handler; | |
return; | |
} | |
if(!handler.__onResolved) { | |
handler.__resolve(value); | |
return; | |
} | |
var ret = handler.__onResolved(value); | |
handler.__resolve(ret); | |
} | |
this.then = function(onResolved) { | |
return new Promise(function(resolve2) { | |
handle({ // from this context | |
__onResolved: onResolved, | |
__resolve: resolve2 // from this2 context - the new/next Promise | |
}); | |
}); | |
}; | |
fn(resolve); | |
} | |
// (A) "Simple" chain: new Promise(fn1).then(fn2).then(fn3); | |
this1 { | |
deffered = { | |
__onResolved: onResolved1, // == "useful payload" | |
__resolve: this2.resolve // == "trigger next" | |
} | |
} | |
this2 { | |
deffered = { | |
__onResolved: onResolved2, | |
__resolve: this3.resolve | |
} | |
} | |
this3 { | |
deffered : null | |
} | |
// (B) Suddenly, fn1() returns a Promise, not a plain value! Then we add the new Promise "before" this1: | |
newValue { | |
deffered = { | |
__onResolved: this1.resolve, // "useful payload" is used to "trigger next", i.e. this1 | |
__resolve: newValue1.resolve | |
} | |
} | |
newValue1 { | |
deffered : null | |
} | |
this1 { | |
deffered = { | |
__onResolved: onResolved1, | |
__resolve: this2.resolve | |
} | |
} | |
this2 { | |
deffered = { | |
__onResolved: onResolved2, | |
__resolve: this3.resolve | |
} | |
} | |
this3 { | |
deffered : null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment