模拟实现Promise

本文通过模拟实现Promise,展示了调用.then方法与resolve/reject的事件计数。内容包括多次调用.then、不同Promise状态变化及错误处理,深入理解Promise的工作原理。
最近复习了一下Promise,决定自己实现一下,加深对Promise流程的理解。当然,这个模拟还不是很完善,比如把events放在了原型上,这个会导致新的MyPromise也受到影响。
/**
 * 使用MyPromise模拟Promise基本功能:
 * MyPromise新建就立即执行其参数fn,这点比较重要
 * fn里面必须调用状态函数resolve或者reject之一
 * 每次.then接受一个处理MyPromise当前状态的回调函数,包括resolve和reject(都是异步执行)
 * 回调函数里面默认或者显式返回一个新的MyPromise,之后的then中的回调是处理新的MyPromise的状态
 * 每次resolve或者reject执行就形成了一个新的MyPromise(并立即执行),后续的then会处理其状态,这样就保证默认的状态不会改变
 *
 * 使用MyPromise.prototype.events保存时间,其实then链是最先执行的
 * 每次resolve或者reject都会使得events中的第一个回调出队列
 *
 * @param fun
 * @constructor
 */
function MyPromise(fun){
    //用于生成MyPromise的id,其实在then执行的时候,都是利用同一个MyPromise将回调保存在events
    this.id = ++MyPromise.prototype.counts;
    var that = this;
    var resolve = function(value){
        var events = MyPromise.prototype.events;
        if(events.length>0){
            console.log("call resolve Promise"+that.id);
            var func = events.shift().res;//取出events队列头中的回调
            //异步执行,实际上是生成了新的MyPromise
            setTimeout(function(){func(value)},0);
        }
    };
    var reject = function(value){
        var events = MyPromise.prototype.events;
        if(events.length>0){
            console.log("call reject Promise"+that.id);
            var func = events.shift().rej;//取出events队列头中的回调
            //异步执行,实际上是生成了新的MyPromise
            setTimeout(function(){func(value)},0);
        }
    };
    //立即执行
    fun(resolve,reject);

}


MyPromise.prototype.counts = 0;
MyPromise.prototype.events = [];//回调队列
/**
 * then方法用于保存回调
 * @param res
 * @param rej
 * @returns {MyPromise}
 */
MyPromise.prototype.then = function(res, rej){
    var events = MyPromise.prototype.events;
    //默认的状态处理,所以可以不断的调用.then并生成新的MyPromise
    var _res = function(value){return new MyPromise(function(res,rej){res(value)});};
    var _rej = function(value){return new MyPromise(function(res,rej){rej(value)});};
    if(res){
        _res = function(value){
            var result = res(value);
            if(result instanceof MyPromise)return result;
            return new MyPromise(function(res,rej){res(value)});
        };
    }
    if(rej){
        _rej = function(value){
            var result = rej(value);
            if(result instanceof MyPromise)return result;
            return new MyPromise(function(res,rej){rej(value)});
        };
    }

    events.push({res:_res,rej:_rej});
    console.log("call .then, Events Counts"+events.length);
    return this;
};

var getJSON = function(json){
    return new MyPromise(function(resolve,reject){
        setTimeout(function(){
            if(json=="6"){
            reject(("error from 3"));
        }else{
            resolve(json);
        }
    },1000);
    });
};
getJSON("1")
    .then(function(json){
        console.log(json);
    })
    .then(function(json){
        console.log(json);
    })
    .then(function(json){
        console.log(json);
        return getJSON("2");
    })
    .then(function(json){
        console.log(json);
    })
    .then(null,function(json){//如果不能正确处理状态,会跳过
        console.log(json);
    })
    .then(function(json){
        console.log(json);
        return getJSON("6");
    })
    .then(function(json){
        console.log(json);
    })
    .then(null,function(json){
        console.log(json);
    })
    .then(function(json){
        console.log(json);
    })
    .then(null,function(json){
        console.log(json);
    });


输出:

call .then, Events Counts1
call .then, Events Counts2
call .then, Events Counts3
call .then, Events Counts4
call .then, Events Counts5
call .then, Events Counts6
call .then, Events Counts7
call .then, Events Counts8
call .then, Events Counts9
call .then, Events Counts10
call resolve Promise1
1
call resolve Promise2
1
call resolve Promise3
1
call resolve Promise4
2
call resolve Promise5
call resolve Promise6
2
call reject Promise7
call reject Promise8
error from 3
call reject Promise9
call reject Promise10
error from 3

### 从零实现一个完整的 Promise 以下是基于 JavaScript 的 `Promise` 完整实现的代码示例及其详细解析: #### 1. 基本结构定义 `Promise` 是一种用于异步编程的对象,它代表了一个最终会完成或者失败的操作的结果。其核心由三个状态组成:`pending`(初始状态)、`fulfilled`(已成功)和 `rejected`(已失败)。以下是一个基本框架。 ```javascript class MyPromise { constructor(executor) { this.state = 'pending'; // 初始状态为 pending this.value = undefined; // 存储成功的值 this.reason = undefined; // 存储失败的原因 this.onFulfilledCallbacks = []; // 成功回调队列 this.onRejectedCallbacks = []; // 失败回调队列 try { executor(this.resolve.bind(this), this.reject.bind(this)); } catch (err) { this.reject(err); } } resolve(value) { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(callback => callback()); } } reject(reason) { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(callback => callback()); } } then(onFulfilled, onRejected) { const realOnFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val; const realOnRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }; let promise2 = new MyPromise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { let x = realOnFulfilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); } }, 0); } if (this.state === 'rejected') { setTimeout(() => { try { let x = realOnRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); } }, 0); } if (this.state === 'pending') { this.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = realOnFulfilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); } }, 0); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = realOnRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (e) { reject(e); } }, 0); }); } }); return promise2; } } // 辅助函数:处理 then 返回的新 Promise function resolvePromise(promise2, x, resolve, reject) { if (x === promise2) { return reject(new TypeError('Chaining cycle detected for promise')); } if ((typeof x === 'object' && x !== null) || typeof x === 'function') { let called = false; try { let then = x.then; if (typeof then === 'function') { then.call( x, y => { if (called) return; called = true; resolvePromise(promise2, y, resolve, reject); }, r => { if (called) return; called = true; reject(r); } ); } else { resolve(x); } } catch (e) { if (called) return; called = true; reject(e); } } else { resolve(x); } } ``` --- #### 2. 解析说明 - **构造器 (`constructor`)** 构造器接收一个执行器函数 `executor`,该函数立即被调用并传入两个参数:`resolve` 和 `reject` 函数[^4]。如果执行器抛出异常,则自动触发 `reject`。 - **状态管理** `state` 属性记录当前 `Promise` 的状态,可能为 `'pending'`, `'fulfilled'` 或 `'rejected'`。只有当状态为 `'pending'` 时才能改变状态。 - **回调队列** 当 `Promise` 被创建时,可能会有多个 `.then()` 注册的回调等待被执行。这些回调会被存储在 `onFulfilledCallbacks` 和 `onRejectedCallbacks` 数组中,并在适当的时候依次调用。 - **`.then()` 方法** 这是 `Promise` 的核心方法之一,允许链式调用。每次调用都会返回一个新的 `Promise` 实例,从而支持复杂的异步操作链条[^4]。 - **辅助函数 (`resolvePromise`)** 此函数专门用来处理 `then` 方法返回的值是否也是一个 `Promise` 对象的情况。如果是,则需要进一步展开直到得到具体值。 --- #### 3. 测试案例 以下是一些测试用例验证其实现是否正确: ```javascript const myPromise = new MyPromise((resolve, reject) => { setTimeout(() => resolve('Success'), 1000); }); myPromise .then(result => { console.log(result); // Success return result.toUpperCase(); }) .then(result => { console.log(result); // SUCCESS }) .catch(error => { console.error('Error:', error); }); ``` --- #### 4. 扩展功能 可以在此基础上继续扩展其他常用的方法,例如: - `catch`: 捕获错误。 - `finally`: 不论成功还是失败均执行清理工作。 - 静态方法如 `MyPromise.all`, `MyPromise.race`, `MyPromise.resolve`, `MyPromise.reject` 等。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值