25行代码实现Promise函数

说明 Promise函数对node后端和前端的重要性就不必多说了,很大一部分程度上解决了恶心的嵌套的回调!现在跟着我来写一个简单的Promise函数吧!
使用 阮一峰老师说的非常好了,有点忘记的同学传送门进去
开始 不啰嗦直接上代码,给你个眼神自己去体会

 class PromiseAProto {
    then(resolve, reject){
        this.resolves = (this.resolves || []).concat(resolve || [])
        this.rejects = (this.rejects || []).concat(reject || [])
        return this;
    }
}
class PromiseA extends PromiseAProto{    
    constructor(cb){
        super(cb)
        cb(() => {
            setTimeout(() => {
                var resolve = this.resolves.shift();
                var ret = resolve && resolve();
                if (this.isPromiseA(ret)) {
                    Object.assign(ret, this)
                }
            }, 0)
        })
    }
    isPromiseA(cb){
        return cb instanceof this.constructor
    }
}

测试 test1

 new PromiseA((resolve, reject) => {
    resolve()
    console.log('hello');
}).then(() => {
    setTimeout(() => {
        console.log("world")
    }, 2000)
})

// 输出为hello   二秒之后输出world

test2

 new PromiseA((resolve, reject) => {
    resolve()
    console.log('hello');
}).then(() => {
    console.log("world")
    return new PromiseA((resolve) => {
        setTimeout(() => {
            resolve();

        }, 1000)
        console.log("hello1")
    })
}).then(() => {
    console.log("over1")
})
// 输出为hello world hello1  一秒之后输出over1

转载于猿2048:➩《25行代码实现Promise函数》

评论

暂无评论