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);
}
);
网友回复
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?
linux上如何运行任意windows程序?
ai能写出比黑客还厉害的零日漏洞等攻击工具攻击任意软件系统工程?
js如何获取浏览器的音频上下文指纹、Canvas指纹、WebGL渲染特征?
为啥ai开始抛弃markdown文本,重新偏好html文本了?
网站有没有办法鉴别访问请求是由ai操控chrome-devtools-mcp发出的?


