简单实现
function myPromise(constructor){
let self = this
self.status = 'pending'
self.value = undefined
self.reason = undefined
function resolve(value){
if(self.status === 'pending'){
self.value = value
self.status = 'resolved'
}
}
function reject(reason){
if(self.status === 'pending'){
self.reason = reason
self.status = 'rejected'
}
}
try{
constructor(resolve,reject)
}catch(e){
reject(e)
}
}
myPromise.prototype.then = function(onFullfilled,onRejected){
let self = this
switch(self.status){
case 'resolved':
onFullfilled(self.value)
break
case 'rejected':
onRejected(self.reason)
break
}
}
const p = new myPromise(function (resolve, reject) {resolve(1)} )
p.then(function (x) { console.log(x) })
可以实现回调
class myPromise {
constructor(executor) {
this.initBind()
this.initValue()
try{
executor(this.resolve, this.reject)
}catch(e){
this.reject(e)
}
}
initBind(){
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
}
initValue() {
this.value = null
this.reason = null
this.status = 'pending'
this.onFullfilledCallbacks = []
this.onRejectedCallbacks = []
}
resolve(value){
if (this.status === 'pending') {
this.status = 'fulfilled'
this.value = value
this.onFullfilledCallbacks.forEach((fn) => fn(this.value))
}
}
reject(reason){
if (this.status === 'pending') {
this.status = 'rejected'
this.reason = reason
this.onRejectedCallbacks.forEach((fn) => fn(this.reject))
}
}
then(onFullfilled,onRejected){
if(this.status === 'fulfilled'){
setTimeout(()=>{
onFullfilled(this.value)},0)
}
if(this.status === 'rejected'){
setTimeout(()=>{
onRejected(this.reason)
},0)
}
if(this.status === 'pending'){
this.onFullfilledCallbacks.push((value) => {
setTimeout(() => {
onFullfilled(value)
})
})
this.onRejectedCallbacks.push((reason) => {
setTimeout(() => {
onRejected(reason)
})
})
}
}
}