promise-full.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /*!
  2. * extend-promise v0.0.6
  3. * Homepage https://github.com/cnwhy/extend-promise#readme
  4. * License BSD-2-Clause
  5. */
  6. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  7. (function (name, factory) {
  8. if (typeof define === 'function' && (define.amd || define.cmd)) {
  9. define([], factory);
  10. } else if (typeof window !== "undefined" || typeof self !== "undefined") {
  11. var global = typeof window !== "undefined" ? window : self;
  12. global[name] = factory();
  13. } else {
  14. throw new Error("加载 " + name + " 模块失败!,请检查您的环境!")
  15. }
  16. })('Promise',function(){
  17. var Promise = require("../promise/setTimeout")
  18. return Promise;
  19. });
  20. },{"../promise/setTimeout":4}],2:[function(require,module,exports){
  21. module.exports = require("./src")(function(fn){setTimeout(fn,0)});
  22. },{"./src":3}],3:[function(require,module,exports){
  23. "use strict";
  24. module.exports = function(nextTick){
  25. var FUN = function(){};
  26. function Resolve(promise, x) {
  27. if(isPromise(x)){
  28. x.then(promise.resolve,promise.reject)
  29. }else if (x && (typeof x === 'function' || typeof x === 'object')) {
  30. var called = false,then;
  31. try {
  32. then = x.then;
  33. if (typeof then === 'function') {
  34. then.call(x, function(y) {
  35. if (called) return;
  36. called = true;
  37. Resolve(promise, y);
  38. }, function(r) {
  39. if (called) return;
  40. called = true;
  41. promise.reject(r);
  42. });
  43. }else {
  44. promise.resolve(x);
  45. }
  46. }catch (e) {
  47. if (!called) {
  48. called = true;
  49. promise.reject(e);
  50. }
  51. }
  52. }else {
  53. promise.resolve(x);
  54. }
  55. }
  56. function isPromise(obj){
  57. return obj instanceof Promise_;
  58. }
  59. function bind(fun,self){
  60. var arg = Array.prototype.slice.call(arguments,2);
  61. return function(){
  62. fun.apply(self,arg.concat(Array.prototype.slice.call(arguments)));
  63. }
  64. }
  65. function Promise_(fun){
  66. //var defer = this.defer = new Defer(this);
  67. var self = this;
  68. this.status = -1; //pending:-1 ; fulfilled:1 ; rejected:0
  69. this._events = [];
  70. var lock = false;
  71. function _resolve(value){
  72. changeStatus.call(self,1,value)
  73. }
  74. function _reject(reason){
  75. changeStatus.call(self,0,reason)
  76. }
  77. function resolve(value){
  78. if(lock) return;
  79. lock = true;
  80. if(self === value){
  81. return _reject(new TypeError("The promise and its value refer to the same object"));
  82. }
  83. Resolve({resolve:_resolve,reject:_reject},value)
  84. }
  85. function reject(reason){
  86. if(lock) return;
  87. lock = true;
  88. _reject(reason);
  89. }
  90. this.resolve = resolve;
  91. this.reject = reject;
  92. if(fun !== FUN && typeof fun == "function"){
  93. try{
  94. fun(this.resolve,this.reject);
  95. }catch(e){
  96. this.reject(e)
  97. }
  98. }
  99. }
  100. Promise_.defer = function(){
  101. var _promise = new Promise_(FUN);
  102. return {
  103. promise: _promise,
  104. resolve: _promise.resolve,
  105. reject: _promise.reject
  106. }
  107. }
  108. Promise_.resolve = function(obj){
  109. if(isPromise(obj)) return obj;
  110. return new Promise_(function(ok,no){
  111. ok(obj);
  112. })
  113. }
  114. Promise_.reject = function(err){
  115. return new Promise_(function(ok,no){
  116. no(err);
  117. })
  118. }
  119. Promise.prototype.toString = function () {
  120. return "[object Promise]";
  121. }
  122. Promise_.prototype.then = function(ok,no){
  123. var status = this.status;
  124. var defer = Promise_.defer()
  125. ,promise = defer.promise
  126. if(!~status){
  127. this._events.push([ok,no,promise]);
  128. }else if(status && typeof ok == "function"){
  129. runThen(ok,this.value,promise,status);
  130. }else if(!status && typeof no == "function"){
  131. runThen(no,this.reason,promise,status)
  132. }else{
  133. if(status) defer.resolve(this.value)
  134. else defer.reject(this.reason);
  135. }
  136. // this._events.push([ok,no,promise]);
  137. // runThens.call(this)
  138. return promise;
  139. }
  140. function changeStatus(status,arg){
  141. var self = this;
  142. if(~this.status) return;
  143. this.status = status;
  144. if(status){
  145. this.value = arg
  146. }else{
  147. this.reason = arg;
  148. }
  149. runThens.call(self)
  150. }
  151. function runThens(){
  152. if(!~this.status) return;
  153. var self = this
  154. ,_event = self._events
  155. ,arg = self.status ? self.value : self.reason
  156. ,FnNumb = self.status ? 0 : 1;
  157. //while(_event.length){
  158. for(var i=0; i<_event.length; i++){
  159. (function(eArr){
  160. var resolve,reject
  161. var fn = eArr[FnNumb]
  162. ,nextQ = eArr[2]
  163. runThen(fn,arg,nextQ,self.status);
  164. })(_event[i])
  165. // })(_event.shift())
  166. }
  167. _event = [];
  168. }
  169. function runThen(fn,arg,nextQ,status){
  170. var resolve = nextQ.resolve
  171. ,reject = nextQ.reject
  172. // if(nextQ){
  173. // resolve = nextQ.resolve
  174. // reject = nextQ.reject
  175. // }
  176. if(typeof fn == 'function'){
  177. nextTick(function(){
  178. var nextPromise;
  179. try{
  180. nextPromise = fn(arg)
  181. }catch(e){
  182. reject(e)
  183. // if(reject)
  184. // else throw e;
  185. return;
  186. }
  187. resolve(nextPromise);
  188. })
  189. }else{
  190. if (status) resolve(arg)
  191. else reject(arg)
  192. }
  193. }
  194. return Promise_;
  195. }
  196. },{}],4:[function(require,module,exports){
  197. var Promise = require('easy-promise/setTimeout');
  198. module.exports = require('../src/polyfills')(Promise);
  199. },{"../src/polyfills":7,"easy-promise/setTimeout":2}],5:[function(require,module,exports){
  200. 'use strict';
  201. var utils = require('./utils')
  202. var isArray = utils.isArray
  203. ,isEmpty = utils.isEmpty
  204. ,isFunction = utils.isFunction
  205. ,isPlainObject = utils.isPlainObject
  206. ,arg2arr = utils.arg2arr
  207. function extendClass(Promise,obj,funnames){
  208. var QClass,source;
  209. if(obj){
  210. source = true
  211. QClass = obj;
  212. }else{
  213. QClass = Promise;
  214. }
  215. function asbind(name){
  216. if(isArray(funnames)){
  217. var nomark = false;
  218. for(var i = 0; i<funnames.length; i++){
  219. if(funnames[i] == name){
  220. nomark = true;
  221. break;
  222. }
  223. }
  224. if(!nomark) return false;
  225. }
  226. if(source){
  227. return !isFunction(QClass[name]);
  228. }
  229. return true;
  230. }
  231. if(!QClass.Promise && Promise != obj) QClass.Promise = Promise;
  232. //defer defer为最基础的实现
  233. if(isFunction(Promise) && isFunction(Promise.prototype.then)){
  234. QClass.defer = function() {
  235. var resolve, reject;
  236. var promise = new Promise(function(_resolve, _reject) {
  237. resolve = _resolve;
  238. reject = _reject;
  239. });
  240. return {
  241. promise: promise,
  242. resolve: resolve,
  243. reject: reject
  244. };
  245. }
  246. }else if(isFunction(Promise.defer)){
  247. QClass.defer = function(){return Promise.defer();}
  248. }else if(isFunction(Promise.deferred)){
  249. QClass.defer = function(){return Promise.deferred();}
  250. }else{
  251. throw new TypeError("此类不支持扩展!")
  252. }
  253. //delay
  254. if(asbind("delay")){
  255. QClass.delay = function(ms,value){
  256. var defer = QClass.defer();
  257. setTimeout(function(){
  258. //console.log('==========')
  259. defer.resolve(value);
  260. },ms)
  261. return defer.promise;
  262. }
  263. }
  264. //resolve
  265. if(asbind("resolve")){
  266. QClass.resolve = function(obj){
  267. var defer = QClass.defer();
  268. defer.resolve(obj);
  269. return defer.promise;
  270. }
  271. }
  272. //reject
  273. if(asbind("reject")){
  274. QClass.reject = function(obj){
  275. var defer = QClass.defer();
  276. defer.reject(obj);
  277. return defer.promise;
  278. }
  279. }
  280. function getall(map,count){
  281. if(!isEmpty(count)){
  282. count = +count > 0 ? +count : 0;
  283. }
  284. return function(promises) {
  285. var defer = QClass.defer();
  286. var data,_tempI = 0;
  287. var fillData = function(i){
  288. var _p = promises[i];
  289. QClass.resolve(_p).then(function(d) {
  290. if(typeof count != 'undefined'){
  291. data.push(d);
  292. }else{
  293. data[i] = d;
  294. }
  295. if (--_tempI == 0 || (!map && count && data.length>=count)) {
  296. defer.resolve(data);
  297. }
  298. }, function(err) {
  299. if (isEmpty(count)) {
  300. defer.reject(err);
  301. }else if(--_tempI == 0){
  302. defer.resolve(data);
  303. }
  304. })
  305. _tempI++;
  306. }
  307. if(isArray(promises)){
  308. data = [];
  309. if(promises.length == 0){defer.resolve(data)};
  310. for(var i = 0; i<promises.length; i++){
  311. fillData(i);
  312. }
  313. }else if(map && isPlainObject(promises)){
  314. var _mark = 0;
  315. data = {}
  316. for(var i in promises){
  317. fillData(i);
  318. _mark++;
  319. }
  320. if(_mark == 0) defer.resolve(data)
  321. }else{
  322. defer.reject(new TypeError("参数错误"));
  323. }
  324. return defer.promise;
  325. }
  326. }
  327. //all
  328. if(asbind("all")){
  329. QClass.all = getall()
  330. }
  331. if(asbind("allMap")){
  332. QClass.allMap = getall(true);
  333. }
  334. if(asbind("some")){
  335. QClass.some = function(proArr,count){
  336. count = +count >= 0 ? +count : 0;
  337. return getall(false,count)(proArr)
  338. }
  339. }
  340. //map
  341. if(asbind("map")){
  342. QClass.map = function(data,mapfun,options){
  343. var defer = QClass.defer();
  344. var promiseArr = [];
  345. var concurrency = options ? +options.concurrency : 0
  346. //无并发控制
  347. if(concurrency == 0 || concurrency != concurrency){
  348. for(var i in data){
  349. promiseArr.push(mapfun(data[i],i,data));
  350. }
  351. QClass.all(promiseArr).then(defer.resolve,defer.reject)
  352. return defer.promise;
  353. }
  354. var k = 0;
  355. var keys = (function(){
  356. var ks = [];
  357. for(var k in data){
  358. ks.push(k);
  359. }
  360. return ks;
  361. })();
  362. function next(){
  363. if(k<keys.length){
  364. var key = keys[k];
  365. var promise = QClass.resolve(mapfun(data[key],key,data)).then(function(v){
  366. next();
  367. return v;
  368. },defer.reject);
  369. promiseArr.push(promise);
  370. concurrency--;
  371. k++;
  372. }else{
  373. QClass.all(promiseArr).then(defer.resolve,defer.reject);
  374. }
  375. }
  376. do{
  377. next()
  378. }while(concurrency>0 && k<keys.length)
  379. return defer.promise
  380. }
  381. }
  382. function race(proArr) {
  383. var defer = QClass.defer();
  384. for (var i = 0; i < proArr.length; i++) {
  385. (function() {
  386. var _i = i;
  387. var _p = proArr[_i];
  388. QClass.resolve(_p).then(function(data) {
  389. defer.resolve(data);
  390. }, function(err) {
  391. defer.reject(err);
  392. })
  393. })()
  394. }
  395. return defer.promise;
  396. }
  397. //any | race
  398. if(asbind("race")){
  399. QClass.race = race;
  400. }
  401. if(asbind("any")){
  402. QClass.any = race;
  403. }
  404. /*封装CPS*/
  405. //callback Adapter
  406. function cbAdapter(defer){
  407. return function(err,data){
  408. if(err) return defer.reject(err);
  409. defer.resolve(data)
  410. }
  411. }
  412. function nfcall(f){
  413. var _this = this === QClass ? null : this;
  414. var defer = QClass.defer();
  415. var argsArray = arg2arr(arguments,1)
  416. argsArray.push(cbAdapter(defer))
  417. f.apply(_this,argsArray)
  418. return defer.promise;
  419. }
  420. if(asbind("nfcall")){
  421. QClass.nfcall = nfcall;
  422. }
  423. if(asbind("nfapply")){
  424. QClass.nfapply = function(f,args){
  425. var _this = this === QClass ? null : this;
  426. var defer = QClass.defer();
  427. if(isArray(args)){
  428. args.push(cbAdapter(defer));
  429. f.apply(_this,args)
  430. }else{
  431. throw TypeError('"args" is not Array')
  432. }
  433. return defer.promise;
  434. }
  435. }
  436. QClass.denodeify = function(f){
  437. var _this = this === QClass ? null : this;
  438. return function(){
  439. return nfcall.apply(_this,[].concat([f],arg2arr(arguments)))
  440. }
  441. }
  442. return QClass;
  443. }
  444. module.exports = extendClass;
  445. },{"./utils":8}],6:[function(require,module,exports){
  446. function extendPrototype(Promise){
  447. var prototype = Promise.prototype;
  448. prototype.done = function(ok,no){
  449. this.then(function(value){
  450. if(typeof ok == "function") setTimeout(function(){ok(value)},0);
  451. },function(err){
  452. if(typeof no == "function") setTimeout(function(){no(err)},0)
  453. else setTimeout(function(){throw err;},0)
  454. })
  455. }
  456. prototype.spread = function(ok,no){
  457. return this.then(function(value){
  458. return ok.apply(null,value);
  459. },no);
  460. }
  461. prototype.fail =
  462. prototype['catch'] = function(no){
  463. return this.then(null,no);
  464. }
  465. /**
  466. * 捕获指定错误
  467. * @param {object} errType 错误类型/错误的值
  468. * @param {Function} fn 处理函数,拒绝值做为参数传入
  469. * @return {Promise}
  470. */
  471. prototype.catchOf = function(errType,fn){
  472. fn = fn || errType;
  473. return this.then(null,function(err){
  474. var futype = typeof fn;
  475. if(futype != "function"){throw err;}
  476. if(errType === fn){
  477. return fn(err);
  478. }
  479. if(errType === err || (typeof errType == 'function' && err instanceof errType)){
  480. return fn(err);
  481. }else{
  482. throw err;
  483. }
  484. });
  485. }
  486. prototype.error = function(no){
  487. return this.catchOf(Error,no);
  488. }
  489. /**
  490. * 不管状态,必定执行,且装态继续传递
  491. * @param {[type]} fun [description]
  492. * @return {Promise}
  493. */
  494. prototype.fin =
  495. prototype['finally'] = function(fun){
  496. var run = function(y,n){try{fun(y,n);}catch(e){}}
  497. return this.then(function(data){
  498. run(data);
  499. return data;
  500. },function(err){
  501. run(null,err);
  502. throw err;
  503. })
  504. }
  505. return Promise;
  506. }
  507. module.exports = extendPrototype;
  508. },{}],7:[function(require,module,exports){
  509. module.exports = function(Promise){
  510. require("../src/extendClass")(Promise),
  511. require("../src/extendPrototype")(Promise)
  512. return(Promise)
  513. }
  514. },{"../src/extendClass":5,"../src/extendPrototype":6}],8:[function(require,module,exports){
  515. 'use strict';
  516. exports.isPlainObject = function(obj) {
  517. if (obj === null || typeof(obj) !== "object" || obj.nodeType || (obj === obj.window)) {
  518. return false;
  519. }
  520. if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
  521. return false;
  522. }
  523. return true;
  524. }
  525. exports.isArray = function(obj){
  526. return Object.prototype.toString.call(obj) == "[object Array]"
  527. }
  528. exports.isFunction = function(obj){
  529. return typeof obj == "function"
  530. }
  531. exports.isEmpty = function(obj){
  532. return typeof obj == 'undefined' || obj === null;
  533. }
  534. exports.arg2arr = function(arg,b,s){
  535. return Array.prototype.slice.call(arg,b,s);
  536. }
  537. },{}]},{},[1])