//constructor
var Promise = function() {
this.callbacks = [];
}
Promise.prototype = {
constructor: Promise,
resolve: function(result) {
this.complete("success", result);
},
reject: function(result) {
this.complete("fail", result);
},
complete: function(type, result) {
while (this.callbacks[0]) {
this.callbacks.shift()[type](result);
}
},
then: function(successHandler, failedHandler) {
this.callbacks.push({
success: successHandler,
fail: failedHandler
});
return this;
}
}
var pro = new Promise();
function ddz() {
setTimeout(function () {
pro.resolve("将数据返回到then中的success函数");
},0);
return pro;
}
var test1 = function (re) {
console.log(re);
pro.reject(re + " 保留上一个then中的数据,并跑到第二个then中的fail函数中")
}
var test2 = function (re) {
console.log(re);
}
ddz().then(test1).then(function(){},test2);//加一个匿名的success函数
运行结果如下:
1、执行ddz函数,由于函数内调用了一个settimeout函数,该函数并不会立即执行,虽然写了0秒后,ddz函数返回一个promise对象
2、该对象又调用then方法,将test1函数添加到callbacks数组中,同时then函数的返回值是promise本身
3、同样的,又调用了then方法将匿名函数和test2添加到callbacks数组中
4、此时同步代码执行完毕,开始执行settime中的代码,此时调用的是resolve函数,因此会执行callbacks【0】中的success,即test1函数,同时将其shift出来,此时test1函数中调用了reject函数
5、执行的是callbacks【0】中的fail函数(此时的callbacks【0】已经不是上次的了,因为已经shift过一次)