/**
* promise 使用方法
* promise 入参函数a,函数a的入参b,c 分别对应resolve函数和rejecte函数
* a().then(res=>{},err=>{})
*/
function MyPromise(fn){
var _this = this
_this.state = 'pendding' // promise 初始状态pendding
_this.value = undefined // 成功的结果 ,执行resolve(value)时候,promise 状态变为resolved,并将传递过来的value 赋值给 _this.value
_this.reason = undefined // 失败的原因, 执行reject(reason)时候, promise 状态变为resolved,并将传递过来的reason 赋值给 _this.reason
function resolve(value){
// 执行resolve函数时时候 ,把promise初始的pendding状态 变成 resolved
if(_this.state === "pendding"){
_this.state = 'resolved'
_this.value = value
}
}
function rejecte(reason){
// 执行resolve函数时时候 ,把promise初始的pendding状态 变成 resolved
if(_this.state === "pendding"){
_this.state = 'rejected'
_this.reason = reason
}
}
try{
// 至于fn里面是执行resolve 还是reject 具体看情况了
fn(resolve,rejecte)
}catch(err){
rejecte()
}
}
MyPromise.prototype.then = function(resolve,reject){
if(this.state === 'resolved' && typeof resolve === "function"){
// 将this.value 传递给resolve函数
resolve(this.value)
}
if(this.state === 'rejected' && typeof reject === "function"){
// 将this.reason 传递给reject函数
reject(this.reason)
}
}
// 自此最简单的promise 封装完成
let a = new MyPromise((resolve,reject)=>{
console.log('promise Begin')
reject('heiheihei=> error ')
})
a.then(res=>{
console.log('res',res)
},err=>{
console.log(err,'err')
})
问题,如果a Promise对象中setTimeout 执行reject会怎样?
代码如下:
let a = new MyPromise((resolve,reject)=>{
console.log('promise Begin')
setTimeout(()=>{
reject('12138')
},2000)
})
此时的reject函数2s之后才执行,promise状态2s之后才变为rejected?
tip:当then里面函数运行时,resolve/reject由于是异步setTImeout执行的,还没有来得及修改state,此时还是PENDING状态;因此我们需要对异步的情况做一下处理。
异步setTimeout中执行的resolve,是因为放在事件队列里面,而promise状态处理函数是同步的,所以导致后来异步的resolve调用不了promise.then(resolve,reject)中的resolve??