Promise实现原理(附源码)

ES6出来很久了,日常开发中经常用到,但是原理比较陌生,最近看了一下Promise/A+规范,实现了一个简易版Promise。


1. Promise 基本用法

const promise = new Promise(function(resolve, reject){
    setTimeout(()=>{
        resolve('resolved')
    })
});

promise.then(function(res){
    console.log(res)
})

2. Promise 状态和值

Promise 对象存在以下三种状态:

  1. Pending(进行中)
  2. Fulfilled(已成功)
  3. Rejected(已失败)

状态只能由 Pending 变为 Fulfilled 或由 Pending 变为 Rejected ,且状态改变之后不会在发生变化,会一直保持这个状态.

Promise 的值是指状态改变时传递给回调函数的值

上文中handle函数包含 resolve 和 reject 两个参数,它们是两个函数,可以用于改变 Promise 的状态和传入 Promise 的值

new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('FULFILLED')
  }, 1000)
})

这里 resolve 传入的 "FULFILLED" 就是 Promise 的值
resolve 和 reject

  • resolve : 将Promise对象的状态从 Pending(进行中) 变为 Fulfilled(已成功)
  • reject : 将Promise对象的状态从 Pending(进行中) 变为 Rejected(已失败)
  • resolve 和 reject 都可以传入任意类型的值作为实参,表示 Promise 对象成功(Fulfilled)和失败(Rejected)的值
    了解了 Promise 的状态和值,接下来,我们为 MyPromise 添加状态属性和值
// 定义Promise的三种状态常量
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

3. Promise构造函数

function MyPromise(fun) {
        const _this = this;
        // 默认状态
        this.state = PEDDING;
        // 成功值
        this.value = undefined;
        // 错误值
        this.reason = undefined;
        // 成功回调集合
        this.fulfilleds = [];
        // 失败回调集合
        this.rejecteds = [];
        
        function resolve(value){
            // 为了适应同步函数,在主线程完成后执行 
            setTimeout(function(){
                if(_this.state === PEDDING){
                    _this.state = FULFILLED;
                    _this.value = value;
                    _this.fulfilleds.forEach(cb => cb(_this.value));
                }
            })
        };

        function reject(value){
         // 为了适应同步函数,在主线程完成后执行
            setTimeout(function(){
                if(_this.state === PEDDING){
                    _this.state = REJECTED;
                    _this.reason = value;
                    _this.rejecteds.forEach(cb => cb(_this.reason));
                }
            })
        };
    
     // 捕获参数执行方法的错误
        try {
            fun(resolve, reject)
        } catch(e) {
            reject(e)
        }
    }

4. Promise 的 then 方法

Promise 对象的 then 方法接受两个参数:onFulfilled 和 onRejected。

    promise.then(onFulfilled, onRejected)

onFulfilled:

  • 当 promise 状态变为成功时必须被调用,其第一个参数为 promise 成功状态传入的值( resolve 执行时传入的值)
  • 在 promise 状态改变前其不可被调用
  • 其调用次数不可超过一次

onRejected:

  • 当 promise 状态变为失败时必须被调用,其第一个参数为 promise 失败状态传入的值( reject 执行时传入的值)
  • 在 promise 状态改变前其不可被调用
  • 其调用次数不可超过一次

多次调用
then 方法可以被同一个 promise 对象调用多次

  • 当 promise 成功状态时,所有 onFulfilled 需按照其注册顺序依次回调
  • 当 promise 失败状态时,所有 onRejected 需按照其注册顺序依次回调

返回
then 方法必须返回一个新的 promise 对象

promise2 = promise1.then(onFulfilled, onRejected);

因此 promise 支持链式调用

promise.then(onFulfilled, onRejected).then(onFulfilled, onRejected);

5. Promise 的 then 实现

MyPromise.prototype.then = function(resolve,reject){
        const _this = this;
        const OnResolve = typeof resolve === 'function' ? resolve : val=>val;
        const OnReject = typeof reject === 'function' ? reject : val=> {throw val};

        return new MyPromise(function(onFulfilled, onRejected){
            const fulfilled = val =>{
                try {
                    // 外层传递的resolve函数返回值是不是MyPromise类
                    const res = resolve(val)
                    if(res instanceof MyPromise){
                        res.then(onFulfilled, onRejected)
                    }else{
                        onFulfilled(res)
                    }

                } catch(e) {
                    onRejected(e);
                }
                
            };
            const rejected  = val =>{
                try {
                    // 外层传递的resolve函数返回值是不是MyPromise类
                    const res = reject(val)
                    if(res instanceof MyPromise){
                        res.then(onFulfilled, onRejected)
                    }else{
                        onFulfilled(res)
                    }
                    
                } catch(e) {
                    onRejected(e);
                }
                
            };
            // 如果状态为pendding,添加成功/失败回调集合
            if(_this.state === PEDDING){
                _this.fulfilleds.push(fulfilled);
                _this.rejecteds.push(rejected);
             };
            // 如果已经成功,直接把结果值传入回调函数
             if(_this.state === FULFILLED){
                resolve(_this.value)
             };
             // 如果失败,直接把结果值传入回调函数
             if(_this.state === REJECTED){
                reject(_this.reason)
             }
        });
    };

6. 最后

至此一个简易版的Promiss类已经完成;

同步例子

     new MyPromise(function(resolve,reject){
        resolve(2)
    }).then(function(v){
        console.log(v);
        return ++v;
    }).then(function(v){
        console.log(v);
        return ++v;
    }).then(function(v){
        console.log(v);
        return ++v; 
    })

结果:

2
3
4

异步例子

     new MyPromise(function(resolve,reject){
        setTimeout(function(){
            resolve(2)
        },3000)
    }).then(function(v){
        console.log(v);
        return ++v;
    }).then(function(v){
        console.log(v);
        return ++v;
    }).then(function(v){
        console.log(v);
        return ++v;
    })

结果:

2
3
4

PS:欢迎大家关注我的公众号【前端专刊】,一起加油吧~


前端专刊
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。