promise自己理解的也不够深刻,具体知识点不在这里细说了
直接上个例子,清晰明了,自己去悟吧
<script type="text/javascript">
//模拟Promise,改善resolve原型方法
var Promise = function () {
this.thens = [];
};
Promise.prototype = {
constructor: Promise,
then: function(callback){
this.thens.push(callback);
return this;
},
resolve: function () {
var t,p;
t = this.thens.shift();
t && (p = t.apply(null, arguments));
while(t && !(p instanceof Promise)){
t = this.thens.shift();
t && (p = t.call(null, p));
}
if(this.thens.length){
p.thens = this.thens;
};
}
}
function f1() {
var promise = new Promise();
setTimeout(function () { console.log(1);
promise.resolve();
}, 5000) return promise;
} function f2() {
var promise = new Promise();
setTimeout(function () {
console.log(2);
promise.resolve();
}, 5000);
return promise;
} function f3() {
var promise = new Promise();
setTimeout(function () { console.log(3);
promise.resolve();
}, 5000) return promise;
} function f4() {
console.log(4);
return 11;
} function f5(x) {
console.log(x+1);
} function f6() {
var promise = new Promise();
setTimeout(function () { console.log(6);
promise.resolve();
}, 5000) return promise;
} function f7() {
console.log(7);
} var that = f1().then(f2).then(f3).then(f4).then(f5).then(f6).then(f7); </script>