Skip to content

Instantly share code, notes, and snippets.

@zeffgo
Created April 3, 2019 13:39
Show Gist options
  • Save zeffgo/0db1a18c6f9aac3f3b0d5e31d1ea24d1 to your computer and use it in GitHub Desktop.
Save zeffgo/0db1a18c6f9aac3f3b0d5e31d1ea24d1 to your computer and use it in GitHub Desktop.
Simple Promise implementation in Node
class Promise {
constructor(fn) {
this.thens = [];
this.state = 'pending';
this.value = undefined;
fn(this.resolve.bind(this));
return this;
}
resolve() {
this.value = arguments[0];
this.state = 'resolved';
while(this.thens.length>0) {
const f = this.thens.pop();
f(this.value);
}
}
then(fn) {
if (this.state==='resolved') {
//console.log('inside then');
fn(this.value);
} else {
this.thens.push(()=>fn(this.value));
}
return this;
}
}
//tests
const p = new Promise((resolve)=>{
setTimeout(()=>{
resolve(1);
}, 100);
});
p.then((value)=>{
console.log(value);
p.then((value2)=>console.log(value2))
.then(function(){
console.log(arguments)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment