function MyPromise(executor){
this.status = 'pending' // 状态 pengding success fail
this.result = '' //结果
this.onSuccessArr = [] //成功回调数组
this.onFailArr = [] //失败回调数组
resolve =(val)=>{ //返回成功
if(this.status!=='pending') return // 以第一次执行为准 后续状态不允许更改
this.result = val
this.status = 'success'
while (this.onSuccessArr.length) {
//将保存的多个then头部删除并执行直到数组为空
this.onSuccessArr.shift()(this.result)
}
}
reject = (val) =>{ // 返回失败
if(this.status!=='pending') return // 以第一次执行为准 后续状态不允许更改
this.result = val
this.status = 'fail'
while (this.onFailArr.length) {
//将保存的多个then头部删除并执行直到数组为空
this.onFailArr.shift()(this.result)
}
}
try{ //如果异常就执行reject
executor(resolve,reject)
}catch(e){
reject(e)
}
}
MyPromise.prototype.then = function (onSuccess,onFail){
//接受成功和失败两个函数
onSuccess = typeof onSuccess === 'function' ? onSuccess : val => val
onFail = typeof onFail === 'function' ? onFail : reason => { throw reason }
//链式调用 返回一个新的promise对象
const newPromise = new MyPromise((resolve,reject)=>{
const resolvePromise = cb => {
try {
// 执行回调的onSuccess函数
const x = cb(this.result)
//判断返回的是否是promise对象
if (x instanceof MyPromise) {
x.then(resolve, reject)
} else {
// 非Promise就直接成功
resolve(x)
}
} catch (err) {
// 处理报错
reject(err)
throw new Error(err)
}
}
if (this.status === 'success') {
// 如果当前为成功状态,执行第一个回调
resolvePromise(onSuccess)
} else if (this.status === 'fail') {
// 如果当前为失败状态,执行第二哥回调
resolvePromise(onFail)
}else if (this.status === 'pending'){
//如果是pending状态 定时器还没执行 就讲他们抛进数组
this.onSuccessArr.push(onSuccess.bind(this))
this.onFailArr.push(onFail.bind(this))
}
})
return newPromise
}
const promise1 = new MyPromise((resolve,reject)=>{
// setTimeout(()=>{
// resolve(1)
// })
resolve(1)
})
promise1.then((res)=>{
return new MyPromise((resolve)=>resolve(333))
}).then((res)=>{
console.log(res)
})
手写promise
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。
推荐阅读更多精彩内容
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/565ad78b4b3b] ),继续...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/3f2ac530ac22] ),继续...
- 1. Promise A+ 规范 官方英文地址:https://promisesaplus.com/ 中文翻译可参...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/b16f412d5ba7] ),继续...