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); } );
网友回复
python中如何让ai接管邮箱自动回复邮件?
Neutralinojs与Electron的区别与不同?
浏览器跨域解决方案有哪些?
有没有开源的solo agent一句话描述就能开发直接运行的前后端应用源代码?
订单支付过程中部分商品库存不足如何处理?
python如何开发一个自定义域名后缀的邮箱系统及登录发送邮件管理web页面?
有没有开源的项目将图片视频声音文字转场特效编排自动生成剪映草稿json文件?
有没有摄像头捕获眼球转动操作鼠标的开源代码?
localstorage如何生成自增的键值对进行增删改查?
python有没有将python脚本与python运行环境一键打包成exe的代码?