码农干货系列【12】--Promise库Version3 - 【当耐特】

2013-04-21 18:30

码农干货系列【12】--Promise库Version3 - 【当耐特】

by 【当耐特】

at 2013-04-21 10:30:00

original http://www.cnblogs.com/iamzhanglei/archive/2013/04/21/3033564.html

代码:

var Promise = function () { this.thens = [] }; Promise.prototype = { resolve: function () { this._handle("done", arguments) }, reject: function () { this._handle("fail", arguments) }, _handle: function (n, t) { var o, s, f, h, r, u, e, c, i; if (this.promiseArr) { for (i = 0, u = this.promiseArr.length; i < u; i++) this.promiseArr[i].resolveCount++; if (this.resolveCount !== this.promiseArr.length && n === "done") return; } while (o = this.thens.shift()) { if (f = o.done, h = o.fail, n === "fail") { h && h.apply(null, t); break; } if (f.length) { for (r = [], i = 0, u = f.length; i < u; i++) e = f[i].apply(null, t), e instanceof Promise && (e.thens = this.thens, r.push(e)); if (c = r.length, c === 0) continue; else { for (i = 0; i < c; i++) r[i].promiseArr = r, r[i].resolveCount = 0; break; } } else { if (s = f.apply(null, t), s instanceof Promise) { s.thens = this.thens; break; } continue; } } }, then: function (n, t) { this.thens.push({ done: n, fail: t }); return this; } }

更新:

去除了when方法,统一使用then,用then的第一个参数类型区分是单task还是多task

增加reject方法,处理task失败

使用:

f1() .then(function () { console.log(arguments) return f2(); }) .then(function () { f3(); }) .then(f4) .then(f5) .then(f6) .then(f7) .then([f8, f9, f10]) .then(f11, function () { console.log("fail"); })     function f1() { var promise = new Promise(); setTimeout(function () {   console.log(1); promise.resolve("from f1"); }, 1500)   return promise; }   function f2() { var promise = new Promise(); setTimeout(function () {   console.log(2); promise.resolve(); }, 2500)   return promise; }   function f3() { var promise = new Promise(); setTimeout(function () {   console.log(3); promise.resolve(); }, 1500)   return promise;   }   function f4() { var promise = new Promise(); setTimeout(function () {   console.log(4); promise.resolve(); }, 1500)   return promise; } function f5() { var promise = new Promise(); setTimeout(function () {   console.log(5); promise.resolve(); }, 1500)   return promise; }   function f6() { console.log(6); } function f7() { var promise = new Promise(); setTimeout(function () {   console.log(7); promise.resolve(); }, 1500)   return promise; }   function f8() { var promise = new Promise(); setTimeout(function () {   console.log(8); promise.resolve(); }, 1500)   return promise; }   function f9() { var promise = new Promise(); setTimeout(function () {   console.log(9); promise.resolve(); }, 5500)   return promise; }   function f10() { var promise = new Promise(); setTimeout(function () {   console.log(10); promise.reject(); }, 1500)   return promise; }   function f11() { var promise = new Promise(); setTimeout(function () {   console.log(11); promise.resolve(); }, 1500)   return promise; }


本文链接:http://www.cnblogs.com/iamzhanglei/archive/2013/04/21/3033564.html,转载请注明。