Skip to content

Instantly share code, notes, and snippets.

@caomingkai
Created August 30, 2019 06:19
Show Gist options
  • Save caomingkai/630f64f88b4457db4fba7c884069a4d7 to your computer and use it in GitHub Desktop.
Save caomingkai/630f64f88b4457db4fba7c884069a4d7 to your computer and use it in GitHub Desktop.
Promise
function Promise(exec) {
this.state = 'pending';
this.value = null;
this.error = null;
this.consumersResolve = [];
this.consumersReject = [];
this.consumersFinally = [];
exec(this.resolve.bind(this), this.reject.bind(this));
}
Promise.prototype.resolve = function(val) {
if (this.state !== 'pending') {
return;
}
this.value = val;
this.state = 'resolved';
this.broadcast();
}
Promise.prototype.reject = function(err) {
if (this.state !== 'pending') {
return;
}
this.error = err;
this.state = 'rejected';
this.broadcast();
}
Promise.prototype.broadcast = function() {
if (this.state === 'pending') {
return;
} else if (this.state === 'resolved') {
this.consumersResolve.forEach( fun => {
fun && fun.call(null, this.value);
})
} else {
this.consumersReject.forEach( fun => {
fun && fun.call(null, this.error);
})
}
this.consumersFinally.forEach( fun => {
fun && fun();
})
}
Promise.prototype.then = function(onResolve, onReject) {
if (onResolve) this.consumersResolve.push(onResolve);
if (onReject) this.consumersReject.push(onReject);
this.broadcast();
return this;
}
Promise.prototype.catch = function(onReject) {
if (onReject) this.consumersReject.push(onReject);
return this;
}
Promise.prototype.finally = function(onFinally) {
if (onFinally) this.consumersFinally.push(onFinally);
}
// TEST
let p = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(5);
}, 1000)
});
p.then(function(val) {
console.log({val});
}).finally(function() {
console.log("Finally executed");
})
@caomingkai
Copy link
Author

easy version Promise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment