实现promise

2020-09-07  本文已影响0人  胡小喵_
/** 

new Promise((resolve, reject) => {

}).then((res) => {

})

*/


class MyPromise {

    constructor(fn) {
        this.res = '';
        this.status = 'pending';
        this.callback = [];

        const resolve = (res) => {
            if (this.status == 'pending') {
                this.status = 'fulfilled';
            }
            this.res = res;

            setTimeout(() => {
                this.callback.forEach((fn) => {
                    fn.onResolved();
                })
            }, 0);
        }
        
        const reject = (res) => {
            this.status = 'REJECTED';
            console.log('reject', res);
        }
    

        fn(resolve, reject);

    }

    then(onResolved, onRejected) {
        return new MyPromise((resolve, reject) => {

            if (this.status==='fulfilled') {
                const resFn = onResolved(this.res);
                if (resFn instanceof MyPromise) {
                    resFn.then((_res) => {
                        resolve(_res);
                    }, (_err) => {
                        reject(_err);
                    })
                } else {
                    resolve(resFn);
                }
            }
            if (this.status==='pending') {
                this.callback.push({
                    onResolved: () => {
                        const resFn = onResolved(this.res);
                        if (resFn instanceof MyPromise) {
                            resFn.then((_res) => {
                                resolve(_res);
                            }, (_err) => {
                                reject(_err);
                            })
                        } else {
                            resolve(resFn);
                        }
                    },
                    onRejected: () => {
                        onRejected(this.res);
                    }
                });
            }
        });
    }

    catch(callback) {
        if (this.status==='rejected') {
            callback(this.res);
        }
    }
}

let a = new MyPromise((resolve, reject) => {

    setTimeout(() => {
        resolve(111);
    }, 2000);
}).then((res) =>{
    console.log('res1', res);

}).then((res)=> {
    console.log('res2', res);

    return new MyPromise((resolve) => {
        setTimeout(() => {
            resolve(333);
        }, 2000);
    });
}).then((res) => {
    console.log('res3', res);
});

console.log('a', a)



上一篇 下一篇

猜你喜欢

热点阅读