class MyPromise {
constructor(callback) {
try {
this.that = this
this.callback = callback;
this.successCallbackArray = []
this.resolveData = []
this.status = "pending"
// this.errorCallback = null
this.all = (P, callback) => {
try {
if (P instanceof Array) {
try {
P.forEach(p => (
p.then((val) => {
try {
this.resolveData.push(val)
if (this.resolveData.length == P.length) {
if (this.status == 'pending') {
callback(this.resolveData)
}
}
} catch (val) {
this.status = 'error'
this.reject(val)
}
}).catch(val => {
this.reject(val)
})
))
} catch (val) {
this.status = 'error'
this.reject(val)
}
} else {
p.then((val) => {
this.resolveData = val
})
callback(this.resolveData)
}
} catch (val) {
this.status = 'error'
this.reject(val)
}
return this
}
this.all = this.all.bind(this)
this.then = (callback) => {
this.successCallbackArray.push(callback)
return this
}
this.catch = (callback) => {
this.errorCallback = callback
return this
};
this.resolve = (val) => {
if (this.status == 'pending') {
setTimeout(() => {
try {
this.successCallbackArray.forEach(callback => {
val = callback(val)
})
} catch (val) {
this.reject(val)
}
})
}
return this
};
this.reject = (val) => {
this.status = 'error'
setTimeout(() => {
this.errorCallback(val)
})
return this
};
try {
if (this.callback instanceof Function) {
this.callback(this.resolve, this.reject)
}
} catch (error) {
this.status = 'error'
this.reject(error)
}
} catch (val) {
this.status = 'error'
this.reject(val)
}
}
}
let p1 = new MyPromise((rev, rej) => {
rej(1)
})
let p2 = new MyPromise((rev, rej) => {
rej(2)
})
let p3 = new MyPromise((rev, rej) => {
rev(3)
})
console.log(1)
new MyPromise((rev, rej) => {
console.log(2)
rev(1)
})
.then(res => {
console.log(4)
console.log('ok' + res)
return 3
}).then(res => {
console.log('ok2' + res)
}).catch((res) => {
console.log(4)
console.log('err' + res)
})
console.log(3)
new MyPromise()
.all([p1, p2, p3], (res) => {
console.log(res)
}).catch((error) => {
console.log(error)
})
手写 Promise --- 原创
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/565ad78b4b3b] ),继续...
- ### 背景 Promise是异步编程的一种解决方案,它可以解决异步回调地狱的问题,防止层层嵌套对程序代码带来的难...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/5a03197461d8] ),继续...
- 1. Promise A+ 规范 官方英文地址:https://promisesaplus.com/ 中文翻译可参...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/b16f412d5ba7] ),继续...