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);
}
);
网友回复
qwen3-omni-flash-realtime实时音视频对话如何记住上下文聊天历史记录?
lmarena.ai如何内置html代码直接预览功能?
qwen3-omni-flash-realtime官方vad python示例代码实时语音聊天没有声音?
如何抵御自定义SSID信标帧攻击?
如果使用网页来搭建一个与gemini的视频聊天通话系统?
gemini如果调用mcp服务?
如何接入多模态ai的api例如gemini或qwen Omni实现ai视频面试打分并保存面试过程?
如何在win10上开发一个自己的拼音输入法?
列式json与传统json有啥不同,如何相互转换?
在哪可以查看任意域名网站的每天的流量?


