自己实现Promise
这样有什么问题嘛,求大佬指教
promise.js
// 构造函数
function MyPromise(fn) {
this.PromiseState = 'pending' // 状态
this.PromiseResult = undefined // 结果
this.FcallBacks = []
this.rejectBacks = []
if ((this instanceof MyPromise) === true) {
if (!fn) {
throw new Error('MyPromise resolver undefined is not a function')
}
const _resolver = function (data) {
if (this.PromiseState === 'pending') {// 等待 ==> 成功
setTimeout(() => {
this.PromiseResult = data
this.PromiseState = 'fulfilled'
this.FcallBacks.forEach(f => {
f()
});
})
}
}
const _reject = function (error) {
if (this.PromiseState === 'pending') {// 等待 ==> 失败
setTimeout(() => {
this.PromiseResult = error
this.PromiseState = 'rejected'
this.rejectBacks.forEach(f => {
f()
});
})
}
}
fn(_resolver.bind(this), _reject.bind(this))
}
}
// then
MyPromise.prototype.then = function (_Fulfilled, _rejectBack) {
if (!this) {
throw new Error('Method MyPromise.prototype.then called on incompatible receiver undefined')
}
// 没有异常执行回调
_Fulfilled != undefined && this.FcallBacks.push(() => {
_Fulfilled(this.PromiseResult)
})
// 有异常捕获异常
_rejectBack != undefined && this.rejectBacks.push(() => {
_rejectBack(this.PromiseResult)
})
return this
}
// finally
MyPromise.prototype.finally = function (callBack) {
setTimeout(() => {
callBack()
})
}
// catch
MyPromise.prototype.catch = function (_Catch) {
this.rejectBacks.push(() => { _Catch(this.PromiseResult) })
this.rejectBacks[_Catch]
return this
}
// resolver
MyPromise.resolve = function (data) {
const p = new MyPromise(function (resolver) {
resolver(data)
})
return p
}
// reject
MyPromise.reject = function (data) {
return new MyPromise(function (resolver, reject) {
reject(data)
})
}
export { MyPromise }
<script type="module">
import { MyPromise } from './promise.js'
let p = new MyPromise(function (resolver, reject) {
setTimeout(() => {
resolver('OK')
})
})
p.then(res => {
console.log(res);
}, err => {
console.log(err, 2);
}).catch(err => {
console.log(err, 1);
}).finally(() => {
console.log('isFinally');
})
let p2 = MyPromise.resolve('OKK')
p2.then(res => {
console.log(res);
})
let p3 = MyPromise.reject('errrrr')
p3.catch(err => {
console.log(err);
})
</script>