Last active
May 11, 2018 09:29
-
-
Save wandroll/7a2ce63fc3849c1a1d9eaf364b87f02a to your computer and use it in GitHub Desktop.
Custom Promise
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
export class CustomPromise { | |
constructor (executor) { | |
if (typeof executor !== 'function'){ | |
throw new Error('You must pass a function') | |
} | |
// Etat de notre promesse | |
let _state = State.PENDING; | |
this.setState = setter(_state) | |
this.getState = getter(_state) | |
// Value représente la valeur actuelle de la promesse une fois résolue | |
let _value = null | |
this.setValue = setter(_value) | |
this.getValue = getter(_value) | |
// Chained concentre l'ensemble des actions a executions à la resolution de la promesse | |
let _chained = [] | |
this.setChained = setter(_chained) | |
this.getChained = getter(_chained) | |
try { | |
executor(resolve, reject); | |
} catch (err){ | |
this.reject(err) | |
} | |
} | |
resolve = res => { | |
if (this.getState() !== State.PENDING) { | |
return | |
} | |
const then = res != null ? res.then : null; | |
if (typeof then === 'function') { | |
return then(resolve, reject); | |
} | |
this.setState(State.FULFILLED); | |
this.setValue(res); | |
this.getChained().forEach(({onFulfilled, onRejected}) => { onFulfilled(res) }); | |
return res; | |
} | |
reject = reason => { | |
if (this.getState() !== State.PENDING) { | |
return | |
} | |
this.setState(State.REJECTED); | |
this.setValue(reason); | |
} | |
then(onFullFiled, onRejected){ | |
// On retourne une promesse pour pouvoir chainer les .then | |
return new CustomPromise((resolve, reject) => { | |
const _onFulfilled = res => { | |
try { | |
resolve(onFulfilled(res)); | |
} catch (err) { | |
reject(err); | |
} | |
}; | |
const _onRejected = err => { | |
try { | |
reject(onRejected(err)); | |
} catch (_err) { | |
reject(_err); | |
} | |
}; | |
switch(this.getState()) { | |
case State.FULFILLED: | |
_onFullFiled(this.getValue()); | |
break; | |
case State.REJECTED: | |
_onRejected(this.getValue()); | |
break; | |
default: | |
this.setChained(this.getChained().push({ onFulfilled: _onFulfilled, onRejected: _onRejected })) | |
} | |
}) | |
} | |
} | |
const State = Object.freeze({ | |
REJECTED: Symbol('REJECTED'), | |
PENDING: Symbol('PENDING'), | |
FULFILLED: Symbol('FULFILLED') | |
}); | |
const setter = key => val => { key = val} | |
const getter = key => () => key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment