function Promise2(fn) {
let self = this;
self.PromiseValue = undefined;
self.status = "pending";
self.onResolvedCallbacks = [];
self.onRejectedCallbacks = [];
const resolve = (value) => {
if (self.status === "pending") {
self.status = "fulfilled";
self.PromiseValue = value;
self.onResolvedCallbacks.forEach((fn) => fn());
}
};
const reject = (reason) => {
if (self.status === "pending") {
self.status = "rejected";
self.PromiseValue = reason;
self.onRejectedCallbacks.forEach((fn) => fn());
}
};
try {
fn(resolve, reject);
} catch (error) {
reject(error);
}
}
Promise2.prototype.then = function(onFulfilled, onRejected) {
if (this.status === "pending") {
this.onResolvedCallbacks.push(() => {
this.PromiseValue = onFulfilled(this.PromiseValue);
});
this.onRejectedCallbacks.push(() => {
this.PromiseValue = onRejected(this.PromiseValue);
});
}
if (this.status === "fulfilled") {
try {
this.PromiseValue = onFulfilled(this.PromiseValue);
} catch (error) {
this.PromiseValue = error;
this.status = "rejected";
}
} else if (this.status === "rejected") {
try {
this.PromiseValue = onRejected(this.PromiseValue);
this.status = "fulfilled";
} catch (error) {
this.PromiseValue = error;
}
}
return this;
};
new Promise2((resolve, reject) => {
console.log("执行同步");
resolve(10);
})
.then((value) => {
console.log("正在执行then");
console.log(value);
let n = value + 1;
return n;
})
.then((value) => {
console.log("执行第二个then");
console.log(value);
});