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