promise是一道经常被问的面试题,所以今天花点时间整理一下
class Promise { //promise 是一个类
constructor(executor){
this.state = "pending" //初始化state为等待状态
this.value = undefined //接受成功的值
this.reason = undefined //接受失败的值
this.onResectedCallback = [] //声明一个数组接收成功要做的事情
this.onRejectedCallback = [] //声明一个数组接收失败要做的事情
let resolve = (value)=>{
// console.log('将状态改成成功,记录成功的信息')
if(this.state !== "pending") return //promise状态凝固
this.state = 'fulfilled' //更新状态
this.value = value //接收成功的参数
this.onResectedCallback.forEach(fn=>fn()) //当状态改变为成功时候调用要做的事情
}
let reject = (reason)=>{
// console.log('将状态改成失败,记录失败的信息')
if(this.state !== "pending") return //promise状态凝固
this.state = 'rejected' //更新状态
this.reason = value //接收失败的参数
this.onRejectedCallback.forEach(fn=>fn())//当状态改变为失败的时候调用要做的事情
}
executor(resolve,reject)
}
// 在原型上添加then方法
then(onFulfilled,onRejected){
// promise2 是链式的后面的promise
let promise2 = new Promise((resolve,reject)=>{
// onFulfilled 如果成功了要被调用
if(this.state ==="fulfilled"){
let x = onFulfilled(this.value)
// 将返回值返回
resolve(x)
}
// onRejected 如果失败了要被调用
if(this.state==="rejected"){
let x = onRejected(this.reason)
// 将返回值返回
reject(x)
}
// 当状态为pending时
if(this.state === 'pending'){
// 将成功的时候要干的事情存起来
this.onResectedCallback.push(()=>{
onFulfilled(this.value)
})
// 将失败的时候要干的事情存起来
this.onRejectedCallback.push(()=>{
onFulfilled(this.reason)
})
}
})
return promise2
}
}
// promise executor
const p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(100)
},1000)
})
// 如果有异步,有可能不是立刻满足条件的,就应该等满足条件后,再来调用这个函数
p.then(res=>{
console.log(res,'1')
})
p.then(res=>{
console.log(res,'2')
})
p.then(res=>{
console.log(res,'3')
})
// 核心要点1:上一个.then要返回一个promise对象
// 核心要点2:下一个.then的参数,要拿到上一个promise的参数
p.then(res=>{
console.log(res)
return 200
}).then(res=>{
console.log(res)
})