promise实现方法

本文详细介绍了JavaScriptPromise对象的内部结构,包括状态管理、resolve和reject函数,以及then方法的注册和回调处理。通过实例展示了如何创建和使用Promise进行异步操作的处理。
摘要由CSDN通过智能技术生成
function Promise(executor) {
    this.state = 'pending'; // Promise的状态
    this.value = undefined; // 保存状态为resolved时的值
    this.reason = undefined; // 保存状态为rejected时的原因
 
    // 保存 then 方法中的回调
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];
 
    // 状态转变为resolved时的函数
    const resolve = (value) => {
        if (this.state === 'pending') {
            this.state = 'resolved';
            this.value = value;
            this.onResolvedCallbacks.forEach(callback => callback(value));
        }
    };
 
    // 状态转变为rejected时的函数
    const reject = (reason) => {
        if (this.state === 'pending') {
            this.state = 'rejected';
            this.reason = reason;
            this.onRejectedCallbacks.forEach(callback => callback(reason));
        }
    };
 
    // 立即执行executor,传入resolve和reject函数
    try {
        executor(resolve, reject);
    } catch (error) {
        reject(error);
    }
}
 
// then 方法用于注册回调函数
Promise.prototype.then = function(onResolved, onRejected) {
    if (this.state === 'resolved') {
        onResolved(this.value);
    }
    if (this.state === 'rejected') {
        onRejected(this.reason);
    }
 
    if (this.state === 'pending') {
        this.onResolvedCallbacks.push(onResolved);
        this.onRejectedCallbacks.push(onRejected);
    }
};
 
// 使用示例
const myPromise = new Promise((resolve, reject) => {
    // 异步操作
    setTimeout(() => {
        // 成功时调用 resolve('成功值')
        // 失败时调用 reject('失败原因')
        resolve('操作成功完成');
    }, 1000);
});
 
myPromise.then(
    (value) => console.log(value), // 成功回调
    (reason) => console.error(reason) // 失败回调
);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

changdapeng007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值