Skip to content

Instantly share code, notes, and snippets.

@nulldef
Created October 30, 2019 09:59
Show Gist options
  • Save nulldef/c8cbcbdcce3b5cf8230b20189b15400a to your computer and use it in GitHub Desktop.
Save nulldef/c8cbcbdcce3b5cf8230b20189b15400a to your computer and use it in GitHub Desktop.
Promise-like JS microlib
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