美文网首页
实现promise

实现promise

作者: 胡小喵_ | 来源:发表于2020-09-07 00:19 被阅读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)



相关文章

网友评论

      本文标题:实现promise

      本文链接:https://www.haomeiwen.com/subject/cjahektx.html