Created
January 8, 2018 10:33
-
-
Save ronaldronson/156b6c2998baf5d4c599a9668def32dc to your computer and use it in GitHub Desktop.
Super simplified Promise example.
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 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