Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active July 11, 2019 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/054162fac95e816ab440060676713bfe to your computer and use it in GitHub Desktop.
Save greggman/054162fac95e816ab440060676713bfe to your computer and use it in GitHub Desktop.
incomplete promise impl
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