Skip to content

Instantly share code, notes, and snippets.

@alkhe
Created June 19, 2015 04:54
Show Gist options
  • Save alkhe/d512a012b12787516726 to your computer and use it in GitHub Desktop.
Save alkhe/d512a012b12787516726 to your computer and use it in GitHub Desktop.
Five-Minute Promise Implementation
let a = new Prom((reject, resolve) => {
setTimeout(() => resolve('Promise A'), 1000);
}).then(result => {
console.log(result);
});
let b = new Prom((reject, resolve) => {
resolve('Promise B');
}).then(result => {
console.log(result);
});
class Prom {
constructor(fn) {
this.resolved = false;
this.rejected = false;
this.result = null;
this.thenHandlers = [];
this.failHandlers = [];
let resolve = result => {
this.resolved = true;
this.result = result;
this.thenHandlers.forEach(fn => fn(result));
};
let reject = result => {
this.rejected = true;
this.result = result;
this.failHandlers.forEach(fn => fn(result));
};
fn(reject, resolve);
}
then(fn) {
if (this.resolved) {
fn(this.result);
} else {
this.thenHandlers.push(fn);
}
return this;
}
fail(fn) {
if (this.rejected) {
fn(this.result);
} else {
this.failHandlers.push(fn);
}
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment