2021-02-23

// promise接受一个函数 有三种 状态 俩个回调
// 写一个构造函数接收一个参数 有三种状态 成功结果 失败结果 成功回调 失败 回调
// 构造函数的原型有一个.then 方法 接收俩个参数 判断状态 如果成功调用 成功函数 失败 调用失败函数 pending 就存起来

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

function Promise(executor) {
    var _this = this
    this.state = PENDING  // 状态
    this.value = undefined  // 成功结果
    this.reason = undefined;  // 失败原因
    this.onFulfilled = [];//Promise resolve时的回调函数集
    this.onRejected = []; //Promise reject时的回调函数集

    function resolve(value) {
        if (_this.state === PENDING) {
            _this.state = FULFILLED
            _this.value = value
            _this.onFulfilled.forEach(fn => fn(value))   // 依次执行成功之后的函数栈
            console.log('_this.onFulfilled:', _this.onFulfilled)
        }
    }
    function reject(reason) {
        if (_this.state === PENDING) {  
            _this.state = REJECTED
            _this.reason = reason
            _this.onRejected.forEach(fn => fn(reason))   // 依次执行失败之后的函数栈
            console.log('_this.onRejected:', _this.onRejected)
        }
    }
    try {
        executor(resolve, reject)
    } catch (e) { }
}
// 接收俩个参数  判断状态      如果成功调用 成功函数     失败 调用失败函数     pending 就存起来
Promise.prototype.then = function (onFulfilled, onRejected) {
    console.log('this:',this)
    if (this.state === PENDING) {
        typeof onFulfilled === 'function' && this.onFulfilled.push(onFulfilled)
        typeof onRejected === 'function' && this.onRejected.push(onRejected)
    }
    if (this.state === FULFILLED) {
        typeof onFulfilled === 'function' && onFulfilled(this.value)
    }
    if (this.state === REJECTED) {
        typeof onRejected === 'function' && onRejected(this.reason)
    }
    console.log('onFulfilled:', onFulfilled)   //then成功的回调函数
    console.log('onRejected:', onRejected)     //then失败的回调函数
}
// module.exports = Promise;
var p = new Promise((resolve, reject) => {
    console.log('开始执行')
    setTimeout(() => {
        console.log('setTimeout执行')
        resolve(4)
    }, 0)
})
p.then((res) => {
    //4 res
    console.log(res, 'res')
})
p.then((res1) => {
    //4 res1
    console.log(res1, 'res1')
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容