function MyPromise(executor) {// 初始化Promise的状态和结果
this._state = 'pending';
this._value = undefined;// 回调函数数组,用于存储成功和失败回调
this._callbacks = [];// 定义resolve函数,用于将Promise状态从pending变为fulfilledconst resolve = (value) => {if (this._state === 'pending') {
this._state = 'fulfilled';
this._value = value;this._callbacks.forEach(callback => {
callback.onFulfilled(value);});}
};
// 定义reject函数,用于将Promise状态从pending变为rejected
const reject = (reason) => {
if (this._state === 'pending') {this._state = 'rejected';
this._value = reason;this._callbacks.forEach(callback => {callback.onRejected(reason);});}
};
// 执行executor函数,传入resolve和reject作为参数try {executor(resolve, reject);
} catch (error) {
reject(error);}}
MyPromise.prototype.then = function (onFulfilled, onRejected) {
if (this._state === 'fulfilled') {onFulfilled(this._value);
} else if (this._state === 'rejected') {onRejected(this._value);
} else if (this._state === 'pending') {this._callbacks.push({onFulfilled,onRejected,});}};
// 示例用法
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => { resolve("成功!"); }, 1000);
});
promise.then((result) => {console.log("成功:" + result);},
(error) => {
console.log("失败:" + error);
});
手写Promise
挣钱养家