美文网首页
Promise的构成原理

Promise的构成原理

作者: 路灯下de男孩 | 来源:发表于2019-04-08 14:49 被阅读0次

自己用类模拟实现 promise
看代码吧

class PromiseOne{ // 定义一个类 
    constructor(fn){
        this.cb = null;
        var self = this
        fn(function(a){ // 运行fn方法,传参两个方法,一个resolve,一个reject。我就写了一个
            // console.log('resolve',a)
            self.cb&&self.cb(a); // 如果cb方法存在就运行,
        });
    }
    then(cb){ // 在运行then方法时给cb赋值   resolve运行时才会有cb这个方法
        this.cb = cb;
    }
}

// promise使用
function sum1(a=0,b=0){ //定义一个方法return 一个promise
    return new PromiseOne(function(resolve,reject){
        setTimeout(function(){
            resolve(a+b);// 2秒后运行resolve传参(a+b)
        },2000)
    })
}

sum1(1,2) // 运行方法 传实参(1,2)
.then(function(m){ // 打点调用then方法
    console.log('then',m); // 结果会在两秒后打印出  3
})

相关文章

网友评论

      本文标题:Promise的构成原理

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