promise实现原理

928 阅读6分钟

前言

1.照猫画虎

  • 1.Promise是类 无需考虑兼容性
  • 2.当new Promise的时候 会传入一个执行器executor 此执行器是立即执行
  • 3.当前executor 给了两个函数参数(resolve, reject) 描述当前promise的状态
  • 4.promise中有三个状态 等待 成功 失败
  • 默认为等待
  • 如果调用 resolve 会走到成功
  • 如果调用 reject 或者发生异常 会走失败
  • 5.每个promise实例都有一个then方法
  • 6.promise 一旦状态变化后不能更改
let Promise = require('./promise.js')

let promise = new Promise((resolve, reject) => {
    resolve('ok')
})

promise.then((value)=>{
  console.log("🚀 ~  success1", value)
}, (reason)=>{
  console.log("🚀 ~  error1", reason)
})

promise.then((value)=>{
  console.log("🚀 ~  success2", value)
}, (reason)=>{
  console.log("🚀 ~  error2", reason)
})

/**
 * @description       三种状态
 * @const PENDING     等待
 * @const FULFILLED   成功
 * @const REJECTED    失败
 */
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
  constructor(executor) {
    this.status = PENDING;    // 状态 默认等待
    this.value = undefined;   // 成功的值
    this.reason = undefined;  // 失败的值

    const resolve = (value) => {
      if (this.status === PENDING) {
        this.value = value
        this.status = FULFILLED
      }
    }
    
    const reject = (reason) => {
      if (this.status === PENDING) {
        this.reason = reason
        this.status = REJECTED
      }
    }

    try {
      // 传入的执行器 默认立即执行
      executor(resolve, reject)
    } catch (error) {
      reject(error)
    }

  }

  then(onFulfilled, onRejected) {
    // 成功的回调
    if (this.status === FULFILLED) {
      onFulfilled(this.value)
    }

    // 失败的回调
    if (this.status === REJECTED) {
      onRejected(this.reason)
    }
  }

}

module.exports = Promise

2.异步处理

  • 发布订阅模式
  • 解决异步如何处理
  • 假如有setTimeout时, 当前上下文执行完 才会执行resolve()
let promise = new Promise((resolve, reject) => {
  setTimeout(()=>{
    resolve('ok')
  }, 3000)
})

promise.then((value)=>{
  console.log("🚀 ~  success1", value)
}, (reason)=>{
  console.log("🚀 ~  error1", reason)
})

promise.then((value)=>{
  console.log("🚀 ~  success2", value)
}, (reason)=>{
  console.log("🚀 ~  error2", reason)
})
/**
 * @description       三种状态
 * @const PENDING     等待
 * @const FULFILLED   成功
 * @const REJECTED    失败
 */
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
    constructor(executor) {
        this.status = PENDING;    // 状态 默认等待
        this.value = undefined;   // 成功的值
        this.reason = undefined;  // 失败的值

        this.onFulfilledCallbacks = [];   // async 存储成功时的回调方法
        this.onRejectedCallbacks  = [];   // async 存储失败时的回调方法
 
        const resolve = (value) => {
            if (this.status === PENDING) {
                this.value = value
                this.status = FULFILLED

                // 异步问题 发布
                this.onFulfilledCallbacks.forEach(fn => fn())
            }
        }
    
        const reject = (reason) => {
            if (this.status === PENDING) {
                this.reason = reason
                this.status = REJECTED

                // 异步问题 发布
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }
 
        try {
            // 传入的执行器 默认立即执行
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
 
   }
 
    then(onFulfilled, onRejected) {
        // 当有异步问题时 订阅
        // 此时状态时默认的PENDING
        if (this.status === PENDING) {
            this.onFulfilledCallbacks.push(() => {
                onFulfilled(this.value)
            })

            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }

        // 成功的回调
        if (this.status === FULFILLED) {
            onFulfilled(this.value)
        }
    
        // 失败的回调
        if (this.status === REJECTED) {
            onRejected(this.reason)
        }
    }
 
}
 
module.exports = Promise

3.链式调用(核心)

  • 1.调用then 会返回一个新的promise
  • 2.then中方法 返回是一个普通值, 会作为下一次 then 的成功结果
  • 3.then中方法 执行出错, 会作为下一次 then 的失败结果
  • 4.then中方法 返回的是一个promise对象 会根据promise的resolve, reject来处理 是走成功还是失败
  • 5.无论then走是成功还是失败 只要返回的是普通值 都会执行下一次then的成功
let Promise = require('./promise.js')

let promise = new Promise((resolve, reject)=>{ resolve('链式回调') })

// then1
let promise2 = promise.then(
  value => { return value + '1' },
  error => { return error + '1' }
);

// 第一种特殊情况 resolvePromise
// let promise2 = promise.then(
//   value => { return promise2 },
//   error => { return error + '1' }
// );

// 第二种特殊情况 resolvePromise
// let promise2 = promise.then(
//   value => {
//         // x 可能是一个promise
//         return new Promise((resolve,reject)=>{
//             setTimeout(() => {
//                 resolve(new Promise((resolve,reject)=>{
//                     setTimeout(() => {
//                         resolve('x是promise');
//                     }, 1000);
//                 }))
//             }, 1000)
//         })
//   },
//   error => { return error + '1' }
// );

// then2
// 🚀 ~ success 链式回调1
promise2.then().then(null).then(
  value => { console.log("🚀 ~ success", value) },
  error => { console.log('🚀 ~ failure', error) }
);

// 也可以这样写
// promise.then(
//   value => { return value + '1' },
//   error => { return error + '1' }
// ).then(
//   value => { console.log("🚀 ~ success", value) },
//   error => { console.log('🚀 ~ failure', error) }
// );

// 链式调用
// 1.解决嵌套回调(地狱回调)
// 2.同步并发
// 3.多个异步处理错误

/**
 * @description       三种状态
 * @const PENDING     等待
 * @const FULFILLED   成功
 * @const REJECTED    失败
 */
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
    constructor(executor) {
        this.status = PENDING;    // 状态 默认等待
        this.value = undefined;   // 成功的值
        this.reason = undefined;  // 失败的值

        this.onFulfilledCallbacks = [];   // async 存储成功时的回调方法
        this.onRejectedCallbacks  = [];   // async 存储失败时的回调方法

        const resolve = (value) => {
            // 如果value值时promise, 接着执行
            if (value instanceof Promise) {
                return value.then(resolve, reject)
            }

            if (this.status === PENDING) {
                this.value = value
                this.status = FULFILLED

                // 异步问题 发布
                this.onFulfilledCallbacks.forEach(fn => fn())
            }
        }
    
        const reject = (reason) => {
            if (this.status === PENDING) {
                this.reason = reason
                this.status = REJECTED

                // 异步问题 发布
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }

        try {
            // 传入的执行器 默认立即执行
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }

}

    then(onFulfilled, onRejected) {
        // 什么也没传 连续调用
        // promise.then().then().then(...)
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
        onRejected = typeof onRejected === 'function' ? onRejected : error => { throw error }

        let promise2 = new Promise((resolve, reject) => {
            // 成功的回调
            // 以成功为例:
            // 1.无论成功还是失败, 是正常值都 下一次then都会走resolve, 否者会走reject, (try catch)
            // 2.如果返回的是promise对象 用setTimeout获取当前的promise2对象
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = onFulfilled(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            }
            
            // 失败的回调
            if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = onRejected(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            }
            
            // 当有异步问题时 订阅
            // 此时状态时默认的PENDING
            if (this.status === PENDING) {
                this.onFulfilledCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onFulfilled(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
    
                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onRejected(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
            }


        })


        return promise2
    }

}

/**
 * @description     处理then返回的结果
 * @param promise2  then返回新promise对象
 * @param x         then参数: onFulfilled, onRejected函数 返回的值, 没有返回就是undefined
 * @param resolve   promise2的resolve
 * @param reject    promise2的reject
 */
function resolvePromise(promise2, x, resolve, reject) {
    // 第一种特殊情况 resolvePromise
    if (promise2 === x) { return reject(new TypeError('TypeError: Chaining cycle detected for promise #<Promise> 死循环')) }
    
    if ((typeof x === 'object' && x !== null) || typeof x === 'function') {
        // 防止别人的写的promise 调用成功后 还调用失败
        let called = false;
        
        try {
            // 第二种特殊情况 resolvePromise
            // 有可能then是通过object.defineProperty实现的
            let then = x.then;
            
            if (typeof then === 'function') {
                // then 认为就是promise了 这样是防止会触发getter 造成的异常错误
                then.call(x, y => {
                        if (called) return;
                        called = true;

                        // 继续解析 直到不是promise
                        resolvePromise(promise2, y, resolve, reject)
                    }, r => {
                        if (called) return;
                        called = true;
                        reject(r);
                    });
            } else {
                // 普通的对象 {} { then: {} }
                resolve(x)
            }

        } catch (error) {
            if (called) return;
            called = true;
            reject(error);
        }

    } else {
        // 普通值
        resolve(x);
    }
}

module.exports = Promise

promise规范测试

  • 安装 npm install promises-aplus-tests -g
  • 执行 promises-aplus-tests promise.js
  • 如果测试没有错误 说明promise写的符合规范
  • 只针对promise里的resolve, reject
// promise.ts文件

// other code....

Promise.deferred = function () {
    let dfd = {};
    dfd.promise = new Promise((resolve,reject)=>{
        dfd.resolve= resolve;
        dfd.reject = reject;
    }); 
    return dfd;
}

module.exports = Promise

其他方法

Promise.resolve, Promise.reject, catch

class Promise {
  // other code ...

  // Promise.resolve
  static resolve(value) {
    return new Promise((resolve, reject) => {
      resolve(value)
    })
  }

  static reject(value){
    return new Promise((resolve,reject)=>{
        reject(value);
    })
  }

  catch(errorFn){
      return this.then(null,errorFn)
  }

}

race

  • 采用最快的Promise.race
  • 其实数组中的每个promise都已执行
  • 一方执行完 就立即停止
  • 主要的最快的已经修改了this.status状态
  • 其他的也执行 但是if判断 跳过
class Promise {

  // other code ...

  static race(promises) {
      return new Promise((resolve, reject) => {
          for (let i = 0; i < promises.length; i++) {
              const p = promises[i];
              if (p && typeof p.then === 'function') {
                  p.then(resolve, reject)
              } else {
                  resolve(p)
              }
          }
      })
  }

}
let Promise = require('./promise.js')

let p1 = new Promise((resolve,reject)=>{
    setTimeout(() => {
        resolve('成功')
    }, 1000);
})

let p2 = new Promise((resolve,reject)=>{
    setTimeout(() => {
        reject('失败')
    }, 500);
})

// 例子1
// ‘失败’
Promise.race([p1, p2]).then(
    v => console.log(v),
    e => console.log(e)
)

// 例子2
// 1
Promise.race([p1, p2, 1]).then(
    v => console.log(v),
    e => console.log(e)
)
// 做一个超时中断
let p3 = new Promise((resolve) => {
    setTimeout(()=>{
        resolve('p3成功')
    }, 3000)
})

function warp(proParams) {
    // 导出中断用的
    let abort;
    let p = new Promise((resolve, reject) => {
        abort = reject
    })

    let result = Promise.race([p, proParams])
    result.abort = abort

    return result
}

let p3IsTimeOut = warp(p3)

p3IsTimeOut.then(
    value => console.log(value),
    error => console.log(error)
)

// end: '已超时一秒'
setTimeout(() => {
    p3IsTimeOut.abort('已超时一秒')
}, 1000)

finally

  • 无论失败 还是成功 都会执行
  • 并且可以继续.then
  • 成功时 cb() 返回的值 不会 往下传递 还是.thenvalue
  • 失败时 执行完 cb() 并抛出错误(错误是会继续往下抛)
  • 为什么使用Promise.resolve?
  • 因为 cb() 执行完 如果返回的值 Promise对象
  • 直接执行val.then(resovle, reject), 并返回新的promise
class Promise {
  // other code ...

  finally(cb) {
        return this.then(
            value => {
                return Promise.resolve(cb()).then(() => value)
            },
            error => {
                return Promise.resolve(cb()).then(() => { throw error })
            }
        )
  }

}
let Promise = require('./source/promise3.js')

let p1 = new Promise((resolve,reject)=>{
    setTimeout(() => {
		    // 结果1
		    resolve('resolve: 成功')
		    // 结果2
        // reject('reject: 失败')
    }, 3000);
})

let p2 = p1.finally(() => {
    return new Promise((resolve, reject) => {
       	setTimeout(() => {
        	resolve('123456');
       	}, 1000);
    })
})

// 结果1
// resolve: 成功
// 结果2
// 🚀 ~ catch reject: 失败
p2.then(value =>{
    console.log(value)
}).catch(error => {
	console.log("🚀 ~ catch", error)
})

node 中的promisify

// a.txt
这是个测试文件
const fs = require('fs')

// const { promisify } = require("util");
// const readFile = promisify(fs.readFile)

// 这是个测试文件
// readFile('./a.txt', 'utf8').then(data => {
//      console.log("🚀 ~ data", data)
// })


function promisify(fn) {
    return function(...args){
        return new Promise((resolve, reject) => {
            fn(...args, (err, data) => {
                if(err) return reject(err);
                resolve(data);
            })
        })
    }
}

let p = promisify(fs.readFile)

// 这是个测试文件
p('./a.txt', 'utf8').then(v => console.log(v))