1、最基本的功能:

function Promise(fn){
    this.arr = [];
    this.then = function(thParam){
        thParam(this.arr);
        //return this;
    };
    var that = this;
    function resolve(parm){
        that.arr.push(parm);
        console.log(parm)
    }
    fn(resolve);
}

var p1 = new Promise(function(resolve){   
    resolve("参数给then");
});
p1.then(function(response){
    console.log(response)
});

2、链式调用

function Promise(fn){
    this.arr = [];
    this.then = function(paramFun){
        var thenParam = paramFun(this.arr[0]);
        this.arr.splice(0,1,thenParam);
        return this;
    };
    var that = this;
    function resolve(parm){
        that.arr.push(parm);
        console.log(parm)
    }
    fn(resolve);
}

var p1 = new Promise(function(resolve){    
    resolve("参数给then");
});
p1.then(function(response){
    console.log(response) //参数给then
    return 1;
}).then(function(response){
    console.log(response)  //1
    return 2;
}).then(function(response){
    console.log(response)  //2
});

参考资料:手写一个Promise


胡椒
17 声望2 粉丝

« 上一篇
js柯里化函数
下一篇 »
js深度克隆