编辑代码

// 手写promise
//  new Promise((resolve,reject)=>{}).then(res=>{}).then(res=>{})

// promise三个状态:pending/fulfilled/rejected
// 状态改变后不可更改
class myPromise {
    constructor(executor) {
        // 传入的是一个函数,并且用到了promise内部的resolve和reject函数
        this.status = 'pending'
        this.value = undefined
        this.onResolvedCallbacks = []; // 成功的回调函数队列
        this.onRejectedCallbacks = [];// 失败的回调函数队列


        const resolve = (data) => {
            // 状态流转为fulfilled
            if (this.status === 'pending') {
                this.status = 'fulfilled'
                this.value = data
                console.log(this.onResolvedCallbacks)
                this.onResolvedCallbacks.forEach(fn => fn())
            }
        }

        const reject = (reason) => {
            if (this.status === 'pending') {
                this.status = 'rejected'
                this.value = reason                
                console.log(this.onRejectedCallbacks)
                this.onRejectedCallbacks.forEach(fn => fn())

            }
        }

        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }

    }

    // then方法,两个参数一个是成功后的回调,一个是失败后的回调
    // then((res)=>{},(error)=>{})

    then(onFulfilled, onRejected) {
        // 判断传入的是否是回调函数
        onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : (value) => value
        onRejected = typeof onRejected == 'function' ? onRejected : (reason) => { throw reason }


        const promise = new myPromise((resolve, reject) => {
            // 执行对应的回调函数
            if (this.status === 'fulfilled') {
                setTimeout(() => {
                    try {
                        const result = onFulfilled(this.value) // 获取结果
                        this.resolvePromise(promise, result, resolve, reject)// 处理结果
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            }

            if (this.status === 'rejected') {
                setTimeout(() => {
                    try {
                        const reason = onRejected(this.value) // 获取结果
                        this.resolvePromise(promise, reason, resolve, reject)// 处理结果
                    } catch (error) {
                        reject(error)
                    }
                }, 0)
            }

            if (this.status === 'pending') {
                this.onResolvedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            const result = onFulfilled(this.value) // 获取结果
                            this.resolvePromise(promise, result, resolve, reject)// 处理结果
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })

                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            const reason = onRejected(this.value) // 获取结果
                            this.resolvePromise(promise, reason, resolve, reject) // 处理结果
                        } catch (error) {
                            reject(error)
                        }
                    }, 0)
                })
            }
        })

        // 返回的是一个promise
        return promise
    }
    resolvePromise(promise, result, resolve, reject) {
        // 判断是不是相同,如果是就promise循环了
        if (promise === result) {
            return reject('Chaining cycle detected for promise')
        }

        // 创建一个开关,防止多次调用
        let called = false

        // 判断result是不是promise,如果是需要继续回调直到变成resolve或者reject状态
        if (result instanceof myPromise) {
            result.then((y) => {
                if (called) return
                called = true
                this.resolvePromise(promise, y, resolve, reject)
            }, (reason) => {
                if (called) return
                called = true
                reject(reason)
            })
            return
        }
        // 如果result不是promise,但是是function
        if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
            try {
                const then = result.then;
                // 判断result有没有then方法,如果有那也是promise
                if (typeof then === 'function') {
                    then.call(result, (y) => {
                        if (called) return
                        called = true
                        this.resolvePromise(promise, y, resolve, reject)
                    }, (reason) => {
                        if (called) return
                        called = true
                        reject(reason)
                    })
                }
            } catch (error) {
                if (called) return
                called = true
                reject(error)
            }
            return
        }

        // 以上情况都没有
        resolve(result)
    }

    static all(promises) {
        return new myPromise((resolve, reject) => {
            const result = []

            promises.forEach((promise, index) => {
                promise.then(res => {
                    result[index] = res

                    if (index === result.length - 1) {
                        resolve(result)
                    }
                }, (reason) => {
                    reject(reason)
                })

            })

        })
    }

    static race(promises) {
        return new myPromise((resolve, reject) => {
            promises.forEach(promise => {
                promise.then(resolve, reject)
            })
        })
    }

    static any(promises) {
        return new myPromise((resolve, reject) => {
            const result = []
            const reasons = []
            promises.forEach(promise => {
                promise.then(res => {
                    result.push(res)
                    if (result.length + reason.length === promises.length && result.length) {
                        resolve(result[0])
                    }
                }, (reason) => {
                    if (result.length + reason.length === promises.length && !result.length) {
                        reject(reasons)
                    }
                    reason.push(reason)
                })
            })
        })
    }

    static allSettled(promises) {
        return new myPromise((resolve, reject) => {
            const result = []

            promises.forEach((promise, index) => {
                promise.then(res => {
                    result[index] = res

                    if (index === result.length - 1) {
                        resolve(result)
                    }
                }, (reason) => {
                    result[index] = reason
                })

            })

        })
    }
}




// 测试代码·
new myPromise((resolve, reject) => {
    console.log("start");
    resolve(100);
})
    .then((res) => {
        console.log(res, "----------res");
        return new myPromise((resolve, reject) => {
            setTimeout(() => {
                resolve(88888);
            }, 1000);
        });
    })
    .then((data) => {
        console.log("xixiixi");
        console.log(data);
    });

console.log("hahhahah");