-
-
Save nulldef/c8cbcbdcce3b5cf8230b20189b15400a to your computer and use it in GitHub Desktop.
Promise-like JS microlib
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
const PENDING = -1 | |
const SUCCESS = 0 | |
const ERROR = 1 | |
class J { | |
constructor (fn) { | |
this.value = null | |
this.state = PENDING | |
this.successReactions = [] | |
this.failureReactions = [] | |
this.completeReactions = [] | |
fn( | |
this.__makeCallback(SUCCESS), | |
this.__makeCallback(ERROR) | |
) | |
} | |
__makeCallback = state => value => { | |
if (this.state !== PENDING) return | |
this.value = value | |
this.state = state | |
this.__emit() | |
} | |
__react = callbacks => { | |
while (callbacks.length > 0) callbacks.shift()(this.value) | |
while (this.completeReactions.length > 0) this.completeReactions.shift()() | |
} | |
__emit = () => { | |
switch (this.state) { | |
case SUCCESS: | |
this.__react(this.successReactions) | |
break | |
case ERROR: | |
this.__react(this.failureReactions) | |
break | |
} | |
} | |
onSuccess = fn => { | |
this.successReactions.push(fn) | |
this.__emit() | |
} | |
onFailure = fn => { | |
this.failureReactions.push(fn) | |
this.__emit() | |
} | |
onComplete = fn => { | |
this.completeReactions.push(fn) | |
this.__emit() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment