class valiPromise {
constructor(fn) {
this.status = 'pending';
this.resolveFnArr = [];
this.rejectFnArr = [];
let resolve = (data) => {
if (this.status === 'pending') {
this.data = data;
this.resolveFnArr.map(item => {
item();
})
this.status = 'fullFilled'
}
}
let reject = (data) => {
if (this.status === 'pending') {
this.data = data;
this.rejectFnArr.map(item => {
item();
})
this.status = 'rejected';
}
}
try {
fn(resolve, reject)
} catch (error) {
reject(error)
}
}
then(fullFilledFn, rejectedFn) {
// console.log('then : ', this.status, 'status', this.data, 'this.data', typeof fullFilledFn, typeof rejectedFn)
if (this.status === 'fullFilled' && typeof fullFilledFn === 'function') {
fullFilledFn(this.data)
}
if (this.status === 'rejected' && typeof rejectedFn === 'function') {
rejectedFn(this.data)
}
// handle async code when async will run then code first and because this.status equal pending up code don't run
if (this.status === 'pending') {
this.resolveFnArr.push(() => {
fullFilledFn(this.data)
})
this.rejectFnArr.push(
() => {
rejectedFn(this.data)
}
)
}
// 链式调用
return this
}
}
function testPromise() {
return new valiPromise(function (resolve, reject) {
setTimeout(() => {
resolve(1000)
}, 2000);
})
}
function testPromise1() {
return new valiPromise(function (resolve, reject) {
setTimeout(() => {
resolve(2000)
}, 2000);
})
}
testPromise().then((data) => {
console.log(data);
testPromise1().then((data) => console.log(data))
})
有参考下面链接
https://www.cnblogs.com/xinggood/p/11836096.html