class Promise {
constructor(executor) {
this.status = 'PENDING';
this.value = '';
this.onFulfill = null;
this.onReject = null;
this.onFulfillCallback = [];
this.onRejectCallback = [];
try {
executor(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(value) {
setTimeout(() => {
if (this.status == 'PENDING') {
this.status = 'FULFILLED';
this.value = value;
this.onFulfillCallback.forEach(callback => callback());
}
});
}
reject(value) {
setTimeout(() => {
if (this.status == 'PENDING') {
this.status = 'REJECTED';
this.value = value;
this.onRejectCallback.forEach(callback => callback());
}
});
}
then(onFulfill, onReject) {
this.onFulfill = typeof onFulfill == 'function' ? onFulfill : value => value;
this.onReject =
typeof onReject == 'function'
? onReject
: err => {
throw err;
};
let Promise2 = new Promise((resolve, reject) => {
if (this.status == 'FULFILLED') {
setTimeout(() => {
try {
let x = this.onFulfill(this.value);
this.resolvePromise(x, Promise2, resolve, reject);
} catch (error) {
reject(error);
}
});
}
if (this.status == 'REJECTED') {
setTimeout(() => {
try {
let x = this.onReject(this.value);
this.resolvePromise(x, Promise2, resolve, reject);
} catch (error) {
reject(error);
}
});
}
if (this.status == 'PENDING') {
this.onFulfillCallback.push(() => {
setTimeout(() => {
try {
let x = this.onFulfill(this.value);
this.resolvePromise(x, Promise2, resolve, reject);
} catch (error) {
reject(error);
}
});
});
this.onRejectCallback.push(() => {
setTimeout(() => {
try {
let x = this.onReject(this.value);
this.resolvePromise(x, Promise2, resolve, reject);
} catch (error) {
reject(error);
}
});
});
}
});
return Promise2;
}
resolvePromise(x, Promise2, resolve, reject) {
if (x === Promise2) {
return reject(new TypeError('不可以循环调用函数哦'));
}
let called;
if (x != null && (typeof x === 'object' || typeof x === 'function')) {
try {
let then = x.then;
if (typeof then === 'function') {
if (called) return;
called = true;
then.call(
x,
value => {
this.resolvePromise(value, Promise2, resolve, reject);
},
reason => reject(reason),
);
} else {
if (called) return;
called = true;
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
if (called) return;
called = true;
resolve(x);
}
}
}
// console.log(1);
let p1 = new Promise((resolve, reject) => {
resolve('成功');
// reject('错误了');
// setTimeout(() => {
// resolve(4);
// console.log(2);
// });
});
p1.then(
res => {
console.log('第一次成功了' + res);
return new Promise((resolve, reject) => {
resolve(
new Promise((resolve, reject) => {
resolve(res + '1231');
}),
);
});
},
err => {
console.log('第一次失败了' + err);
throw err + err;
// return err + err;
},
).then(
res => {
console.log('第二次成功了' + res);
},
err => {
console.log('第二次失败了' + err);
},
);
11-21
616
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)