Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Add Comment
Please, Sign In to add comment