實現一個簡單的promise

一、最基本的功能:segmentfault

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)
});

二、鏈式調用this

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
});

參考資料:手寫一個Promisecode

相關文章
相關標籤/搜索