Last active
July 11, 2019 18:50
-
-
Save greggman/054162fac95e816ab440060676713bfe to your computer and use it in GitHub Desktop.
incomplete promise impl
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
function MyPromise(fn) { | |
let status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected | |
function makeQueue(neededStatus) { | |
return { | |
neededStatus, | |
fns: [], | |
do() { | |
if (status === neededStatus) { | |
if (neededStatus === 2 && this.fns.length === 0) { | |
console.error('uncaught error'); | |
} | |
while(this.fns.length) { | |
this.fns.shift()(this.value); | |
} | |
} | |
}, | |
handle(v) { | |
if (status) throw Error('can not set, already handled'); | |
status = neededStatus; | |
this.value = v; | |
this.do(); | |
}, | |
}; | |
} | |
const thenQueue = makeQueue(1); | |
const catchQueue = makeQueue(2); | |
const resolve = thenQueue.handle.bind(thenQueue); | |
const reject = catchQueue.handle.bind(catchQueue); | |
function makeChain(queue) { | |
return function(fn) { | |
let fns; | |
const promise = new MyPromise(function(resolve, reject) { | |
fns = [undefined, resolve, reject]; | |
}); | |
queue.fns.push(function(r) { | |
fns[queue.neededStatus](fn(r)); | |
}); | |
queue.do(); | |
return promise; | |
}; | |
} | |
this.then = makeChain(thenQueue); | |
this.catch = makeChain(catchQueue); | |
try { | |
fn(resolve, reject); | |
} catch (e) { | |
reject(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment