function MyPromise(executor) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.status === 'pending') {
this.status = 'resolved';
this.value = value;
this.onResolvedCallbacks.forEach(callback => callback());
}
};
const reject = (reason) => {
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
if (this.status === 'resolved') {
onFulfilled(this.value);
} else if (this.status === 'rejected') {
onRejected(this.reason);
} else if (this.status === 'pending') {
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
});
this.onRejectedCallbacks.push(() => {
onRejected(this.reason);
});
}
};
const myPromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功的结果');
}, 1000);
});
myPromise.then(
result => {
console.log('成功:', result);
},
reason => {
console.log('失败:', reason);
}
);