Created
April 3, 2019 13:39
-
-
Save zeffgo/0db1a18c6f9aac3f3b0d5e31d1ea24d1 to your computer and use it in GitHub Desktop.
Simple Promise implementation in Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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