一、最基本的功能: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