Skip to content

Instantly share code, notes, and snippets.

@ronaldronson
Created January 8, 2018 10:33
Show Gist options
  • Save ronaldronson/156b6c2998baf5d4c599a9668def32dc to your computer and use it in GitHub Desktop.
Save ronaldronson/156b6c2998baf5d4c599a9668def32dc to your computer and use it in GitHub Desktop.
Super simplified Promise example.
const THEN = 'then';
const CATCH = 'catch';
class Prrromise {
static get THEN() {
return THEN;
}
static get CATCH() {
return CATCH;
}
constructor(fn) {
this.q = [];
/** @TODO move out from constructor */
this.then = this._pusher(Prrromise.THEN);
this.catch = this._pusher(Prrromise.CATCH);
this._onHandle = this._onHandle.bind(this);
this._onReject = this._onReject.bind(this);
fn(this._onHandle, this._onReject);
}
_onHandle(val) {
try {
for (let i = 0, l = this.q.length; i < l; i++) {
const { type, fn } = this.q.shift();
if (Prrromise.CATCH === type) continue;
val = fn(val);
}
} catch(err) {
this._onReject(err);
}
}
_onReject(err) {
let val;
const i = this.q.findIndex(({ type }) => type === Prrromise.CATCH);
this.q = this.q.slice(i);
const fn = this.q.shift();
try {
val = fn(err);
} catch(err) {
this._onReject(err);
}
this._onHandle(val);
}
_pusher(type) {
return (fn) => {
this.q.push({ fn, type });
return this;
};
}
}
module.exports = Prrromise;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment