1. promise核心
// 封装promise
// 1. Promise 就是一个类,在执行这个类的时候,需要传递一个执行器进去,执行去会立即执行
// 2. Promise 中有三个状态,分别为:成功(fulfilled)、失败(rejected)、等待(pending);一旦状态确定就不可更改
// 3. resolve和reject函数用来更改状态
// 4. then 方法内部做的事情就是判断状态,根据状态调用不同的回调函数(成功失败)
// 5. then 成功回调有一个参数,表示成功之后的值,then失败回调有一个参数,表示失败的原因

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

class MyPromise{
    // 当前执行状态
    status = PENDING
    // 成功值
    value = undefined
    // 失败原因
    reason = undefined

    // new Promise是立即执行
    constructor(executor){
        executor(this.resolve,this.reject)
    }

    resolve = value => {
        // 如果状态不在等待 阻止程序向下执行
        if(this.status !== PENDING)return
        // 状态变更为成功
        this.status  = FULFILLED
        // 保存成功之后的值
        this.value = value
    }

    reject = reason => {
        if(this.status !== PENDING)return
        this.status = REJECTED
        this.reason = reason
    }

    // then中的回调
    then(successCallback, failCallback){
        if(this.status === FULFILLED){
            successCallback(this.value)
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }
    }
}

// node提供的导出方式
module.exports = MyPromise

使用

const MyPromise = require('./MyPromise')

let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})
promise加入异步逻辑

前面的promise没有加异步的情况。增加异步就是在then中判断,如果状态没有变更,保存成功回调和失败回调;在resolve或reject时判断是否有需要执行的成功或者失败回调,有就执行

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

class MyPromise{
    // 当前执行状态
    status = PENDING
    // 成功值
    value = undefined
    // 失败原因
    reason = undefined
    // 成功回调
    successCallback = undefined
    // 失败回调
    failCallback = undefined

    // new Promise是立即执行
    constructor(executor){
        executor(this.resolve,this.reject)
    }

    resolve = value => {
        // 如果状态不在等待 阻止程序向下执行
        if(this.status !== PENDING)return
        // 状态变更为成功
        this.status  = FULFILLED
        // 保存成功之后的值
        this.value = value
        // 判断成功回调是否存在 如果存在 调用
        this.successCallback && this.successCallback(this.value)
    }

    reject = reason => {
        if(this.status !== PENDING)return
        this.status = REJECTED
        this.reason = reason
    }

    // then中的回调
    then(successCallback, failCallback){
        if(this.status === FULFILLED){
            successCallback(this.value)
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback = successCallback
            this.failCallback = failCallback
        }
    }
}

module.exports = MyPromise
then方法多次调用添加多个处理函数
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise{
    // 当前执行状态
    status = PENDING
    // 成功值
    value = undefined
    // 失败原因
    reason = undefined
    // 成功回调
    successCallback = []
    // 失败回调
    failCallback = []

    // new Promise是立即执行
    constructor(executor){
        executor(this.resolve,this.reject)
    }

    resolve = value => {
        // 如果状态不在等待 阻止程序向下执行
        if(this.status !== PENDING)return
        // 状态变更为成功
        this.status  = FULFILLED
        // 保存成功之后的值
        this.value = value
        // 判断成功回调是否存在 如果存在 调用
        while(this.successCallback.length){
            this.successCallback.shift()(this.value)
        }
    }

    reject = reason => {
        if(this.status !== PENDING)return
        this.status = REJECTED
        this.reason = reason
        while(this.failCallback.length){
            this.failCallback.shift()(this.reason)
        }
    }

    // then中的回调
    then(successCallback, failCallback){
        if(this.status === FULFILLED){
            successCallback(this.value)
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    }
}

module.exports = MyPromise




let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})
promise.then(value => {
    console.log(value);
})
promise.then(value => {
    console.log(value);
})
then方法的链式调用

链式调用1

then(successCallback, failCallback){
    // 返回一个新的promise,新的promise状态原始都是pending
    let promise2 = new MyPromise((resolve, reject) => {
        // 这里面的this是上一个promise的this
        if(this.status === FULFILLED){
            let x = successCallback(this.value);
            resolve(x) // 这里执行新的promise里面的resolve 改为this.resolve就不行
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    })
    return promise2
}

let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})
promise.then(value => {
    console.log(value);
    return 100;
}).then(value => {
    console.log(value);
})

链式调用2

function resolvePromise(x, resolve, reject) {
    // 判断 x 的值是普通值还是 primise 对象
    // 如果是普通值 直接调用 resolve 
    // 如果是 promise 对象 查看 promise 对象返回的结果
    // 再根据 promise 对象的返回结果 决定调用 resolve 还是 调用 reject (这两都是外部promise的方法)

    if (x instanceof MyPromise) {
        // promise 对象
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x)
    }
}
then(successCallback, failCallback){
    let This = this;
    let promise2 = new MyPromise((resolve, reject) => {
        if(this.status === FULFILLED){
            let x = successCallback(this.value);
            resolvePromise(x,resolve,reject);
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    })
    return promise2
}



const MyPromise = require('./MyPromise')

let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})

function other(){
    return new MyPromise((resolve, reject) => {
        resolve('other')
    })
}

promise.then(value => {
    console.log(value);
    return other()
}).then(res => {
    console.log(res);
})
then链式调用识别对象自己返回自己
let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})


let p1 = promise.then(value => {
    console.log(value);
    return p1
})
p1.then(res => {
    console.log(res);
},err => {
    console.log(err);
})






function resolvePromise(promise2,x, resolve, reject) {
    // 判断 x 的值是普通值还是 primise 对象
    // 如果是普通值 直接调用 resolve 
    // 如果是 promise 对象 查看 promise 对象返回的结果
    // 再根据 promise 对象的返回结果 决定调用 resolve 还是 调用 reject

    if(promise2 === x){
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        // promise 对象
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x)
    }
}

then(successCallback, failCallback){
    let This = this;
    let promise2 = new MyPromise((resolve, reject) => {
        if(this.status === FULFILLED){
            setTimeout(()=>{
                let x = successCallback(this.value);
                resolvePromise(promise2,x,resolve,reject);
            },0)
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    })
    return promise2
}
捕获错误

执行器里面的错误,将错误信息存入错误原因,在then的时候第二个回调打印这个错误

// new Promise是立即执行
constructor(executor) {
    try{
        executor(this.resolve, this.reject)
    }catch(e){
        this.reject(e)
    }
}


let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})

promise.then(res => {
    console.log(res);
},err => {
    console.log(err);
})

then里面的错误,在后面的then里面输出

let promise = new MyPromise((resolve, reject) => {
    resolve('成功')
})

promise.then(res => {
    console.log(res);
    throw new Error('then error')
}).then(res => {
    console.log(res);
},err => {
    console.log(err);
})



then(successCallback, failCallback){
    let This = this;
    let promise2 = new MyPromise((resolve, reject) => {
        if(this.status === FULFILLED){
            setTimeout(()=>{
                try{
                    let x = successCallback(this.value);
                    resolvePromise(promise2,x,resolve,reject);
                }catch(e){
                    reject(e)
                }
            },0)
        } else if(this.status === REJECTED) {
            failCallback(this.reason)
        }else{
            // 等待
            // 将成功回调和失败回调存储起来
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    })
    return promise2
}
处理一下异步和其它的错误
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    // 当前执行状态
    status = PENDING
    // 成功值
    value = undefined
    // 失败原因
    reason = undefined
    // 成功回调
    successCallback = []
    // 失败回调
    failCallback = []

    // new Promise是立即执行
    constructor(executor) {
        try{
            executor(this.resolve, this.reject)
        }catch(e){
            this.reject(e)
        }
    }

    resolve = value => {
        // 如果状态不在等待 阻止程序向下执行
        if (this.status !== PENDING) return
        // 状态变更为成功
        this.status = FULFILLED
        // 保存成功之后的值
        this.value = value
        // 判断成功回调是否存在 如果存在 调用
        while (this.successCallback.length) {
            this.successCallback.shift()()
        }
    }

    reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        while (this.failCallback.length) {
            this.failCallback.shift()()
        }
    }

    // then中的回调
    then(successCallback, failCallback){
        // 每次this都是上一个promise。
        let This = this;
        let promise2 = new MyPromise((resolve, reject) => {
            if(this.status === FULFILLED){
                setTimeout(()=>{
                    try{
                        let x = successCallback(this.value);
                        resolvePromise(promise2,x,resolve,reject);
                    }catch(e){
                        reject(e)
                    }
                },0)
            } else if(this.status === REJECTED) {
                setTimeout(()=> {
                    try{
                        let x = failCallback(this.reason);
                        resolvePromise(promise2,x,resolve,reject);
                    }catch(e){
                        reject(e)
                    }
                })
            }else{
                // 等待
                // 将成功回调和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout(()=>{
                        try{
                            let x = successCallback(this.value);
                            resolvePromise(promise2,x,resolve,reject);
                        }catch(e){
                            reject(e)
                        }
                    },0)
                })
                this.failCallback.push(() => {
                    setTimeout(()=> {
                        try{
                            let x = failCallback(this.reason);
                            resolvePromise(promise2,x,resolve,reject);
                        }catch(e){
                            reject(e)
                        }
                    })
                })
            }
        })
        return promise2
    }


}

function resolvePromise(promise2,x, resolve, reject) {
    // 判断 x 的值是普通值还是 primise 对象
    // 如果是普通值 直接调用 resolve 
    // 如果是 promise 对象 查看 promise 对象返回的结果
    // 再根据 promise 对象的返回结果 决定调用 resolve 还是 调用 reject

    if(promise2 === x){
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        // promise 对象
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x)
    }
}

module.exports = MyPromise
then方法的参数变为可选参数
let promise = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('成功')
    },1000)
})

promise.then()
.then(res => {
    console.log(res);
})



then(successCallback, failCallback){
    // 给then回调赋一个方法,传入什么返回什么
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => {throw reason}
    
    ...
}
promise.all 方法
let p1 = new Promise((resolve, reject) => {
    setTimeout(()=>{
        resolve('p1')
    },2000)
})
let p2 = new Promise((resolve, reject) => {
    setTimeout(()=>{
        resolve('p2')
    },0)
})
Promise.all(['a','b',p1,p2,'c']).then(res => {console.log(res)})
// ['a','b','p1','p2','c']
// 全部执行完,然后按给定顺序返回值




static all(array){
    let result = [];
    let index = 0
   
    return new MyPromise((resolve, reject) => {
    	// 放在里面才能使用resolve
	     function addData (key, value) {
	        result[key] = value;
	        index ++
	        if(index === array.length){
	            resolve(result)
	        }
	    }
        for(let i = 0; i < array.length; i++){
            let current  = array[i];
            if(current instanceof MyPromise){
                // promise对象
                current.then(value => addData(i,value), reason => reject(reason))
            }else{
                // 普通
                addData(i, array)
            }
        }
        // 这时是for循环结束就执行了,result还没全
        // resolve(result)
    })
}
promise.resolve
const MyPromise = require('./MyPromise')

let p = new MyPromise((resolve, reject) => {
    resolve(99)
})

MyPromise.resolve(10).then(res => {console.log(res);})
MyPromise.resolve(p).then(res => {console.log(res);})



static resolve(value){
    if(value instanceof MyPromise){
        // promise对象
        return value;
    }else{
        // 普通
        return new MyPromise((resolve,reject) => {
            resolve(value)
        })
    }
}
promise finally
finally(callback){
    return this.then(value => {
        callback()
        return value
    },reason => {
        callback()
        throw reason
    })
}


finally(callback){
    return this.then(value => {
        return MyPromise.resolve(callback()).then(() => value)
    },reason => {
        return MyPromise.resolve(callback()).then(() => {throw reason})
    })
}
promise catch
catch(failCallback){
    return this.then(undefined, failCallback)
}