class Promise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback(value));
}
};
let reject = reason => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};
try {
// 立即执行函数
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
if (this.state === 'fulfilled') {
try {
let x = onFulfilled(this.value);
this.handleThenCallback(x, resolve, reject);
} catch (err) {
reject(err);
}
}
if (this.state === 'rejected') {
try {
let x = onRejected(this.reason);
this.handleThenCallback(x, resolve, reject);
} catch (err) {
reject(err);
}
}
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(value => {
try {
let x = onFulfilled(value);
this.handleThenCallback(x, resolve, reject);
} catch (err) {
reject(err);
}
});
this.onRejectedCallbacks.push(reason => {
try {
let x = onRejected(reason);
this.handleThenCallback(x, resolve, reject);
} catch (err) {
reject(err);
}
});
}
});
}
handleThenCallback(x, resolve, reject) {
if (x instanceof Promise) {
// 如果 x 是一个 Promise,则等待其状态变更
x.then(resolve, reject);
} else {
// 如果 x 是普通值,则直接将其作为新 Promise 的值进行 resolve
resolve(x);
}
}
// 可以添加其他方法,如 catch、finally 等
}
// 使用示例
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve('Success!');
} else {
reject('Failure!');
}
}, 1000);
});
promise
.then(
value => {
console.log('Resolved:', value);
return 'New Value';
},
reason => {
console.log('Rejected:', reason);
throw new Error('New Error');
}
)
.then(
value => {
console.log('Resolved:', value);
},
reason => {
console.log('Rejected:', reason.message);
}
);
网友回复
如何破解绕开seedance2.0真人照片生成视频 限制?
python有哪些算法可以将视频中的每个帧图片去除指定区域水印合成新的视频?
iphone的激光雷达数据能否实时传输到three三维空间中?
豆包sora等ai视频生成大模型生成的视频水印如何去除?
python如何实现在电脑上拨号打电话给手机?
具身机器人与人形机器人区别?
nodejs如何将一个完整的js代码文件切割成不同的部分混淆后动态加载进入html运行?
为啥windows.onerror捕获js错误是这样的{"message":"Script error.","source":"","lineno":0,"colno":0,"stack":null,
2026年ai将全面接管编程?
WebMCP是干啥的?


