PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/when/3.6.0/when.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 273 lines | 118 code | 35 blank | 120 comment | 3 complexity | 3cce7a4d3cfe266ae78ea57e63a673cf MD5 | raw file
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /**
  3. * Promises/A+ and when() implementation
  4. * when is part of the cujoJS family of libraries (http://cujojs.com/)
  5. * @author Brian Cavalier
  6. * @author John Hann
  7. * @version 3.6.0
  8. */
  9. (function(define) { 'use strict';
  10. define(function (require) {
  11. var timed = require('./lib/decorators/timed');
  12. var array = require('./lib/decorators/array');
  13. var flow = require('./lib/decorators/flow');
  14. var fold = require('./lib/decorators/fold');
  15. var inspect = require('./lib/decorators/inspect');
  16. var generate = require('./lib/decorators/iterate');
  17. var progress = require('./lib/decorators/progress');
  18. var withThis = require('./lib/decorators/with');
  19. var unhandledRejection = require('./lib/decorators/unhandledRejection');
  20. var TimeoutError = require('./lib/TimeoutError');
  21. var Promise = [array, flow, fold, generate, progress,
  22. inspect, withThis, timed, unhandledRejection]
  23. .reduce(function(Promise, feature) {
  24. return feature(Promise);
  25. }, require('./lib/Promise'));
  26. var slice = Array.prototype.slice;
  27. // Public API
  28. when.promise = promise; // Create a pending promise
  29. when.resolve = Promise.resolve; // Create a resolved promise
  30. when.reject = Promise.reject; // Create a rejected promise
  31. when.lift = lift; // lift a function to return promises
  32. when['try'] = attempt; // call a function and return a promise
  33. when.attempt = attempt; // alias for when.try
  34. when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  35. when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
  36. when.join = join; // Join 2 or more promises
  37. when.all = all; // Resolve a list of promises
  38. when.settle = settle; // Settle a list of promises
  39. when.any = lift(Promise.any); // One-winner race
  40. when.some = lift(Promise.some); // Multi-winner race
  41. when.race = lift(Promise.race); // First-to-settle race
  42. when.map = map; // Array.map() for promises
  43. when.filter = filter; // Array.filter() for promises
  44. when.reduce = reduce; // Array.reduce() for promises
  45. when.reduceRight = reduceRight; // Array.reduceRight() for promises
  46. when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
  47. when.Promise = Promise; // Promise constructor
  48. when.defer = defer; // Create a {promise, resolve, reject} tuple
  49. // Error types
  50. when.TimeoutError = TimeoutError;
  51. /**
  52. * Get a trusted promise for x, or by transforming x with onFulfilled
  53. *
  54. * @param {*} x
  55. * @param {function?} onFulfilled callback to be called when x is
  56. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  57. * will be invoked immediately.
  58. * @param {function?} onRejected callback to be called when x is
  59. * rejected.
  60. * @param {function?} onProgress callback to be called when progress updates
  61. * are issued for x. @deprecated
  62. * @returns {Promise} a new promise that will fulfill with the return
  63. * value of callback or errback or the completion value of promiseOrValue if
  64. * callback and/or errback is not supplied.
  65. */
  66. function when(x, onFulfilled, onRejected) {
  67. var p = Promise.resolve(x);
  68. if(arguments.length < 2) {
  69. return p;
  70. }
  71. return arguments.length > 3
  72. ? p.then(onFulfilled, onRejected, arguments[3])
  73. : p.then(onFulfilled, onRejected);
  74. }
  75. /**
  76. * Creates a new promise whose fate is determined by resolver.
  77. * @param {function} resolver function(resolve, reject, notify)
  78. * @returns {Promise} promise whose fate is determine by resolver
  79. */
  80. function promise(resolver) {
  81. return new Promise(resolver);
  82. }
  83. /**
  84. * Lift the supplied function, creating a version of f that returns
  85. * promises, and accepts promises as arguments.
  86. * @param {function} f
  87. * @returns {Function} version of f that returns promises
  88. */
  89. function lift(f) {
  90. return function() {
  91. return _apply(f, this, slice.call(arguments));
  92. };
  93. }
  94. /**
  95. * Call f in a future turn, with the supplied args, and return a promise
  96. * for the result.
  97. * @param {function} f
  98. * @returns {Promise}
  99. */
  100. function attempt(f /*, args... */) {
  101. /*jshint validthis:true */
  102. return _apply(f, this, slice.call(arguments, 1));
  103. }
  104. /**
  105. * try/lift helper that allows specifying thisArg
  106. * @private
  107. */
  108. function _apply(f, thisArg, args) {
  109. return Promise.all(args).then(function(args) {
  110. return f.apply(thisArg, args);
  111. });
  112. }
  113. /**
  114. * Creates a {promise, resolver} pair, either or both of which
  115. * may be given out safely to consumers.
  116. * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
  117. */
  118. function defer() {
  119. return new Deferred();
  120. }
  121. function Deferred() {
  122. var p = Promise._defer();
  123. function resolve(x) { p._handler.resolve(x); }
  124. function reject(x) { p._handler.reject(x); }
  125. function notify(x) { p._handler.notify(x); }
  126. this.promise = p;
  127. this.resolve = resolve;
  128. this.reject = reject;
  129. this.notify = notify;
  130. this.resolver = { resolve: resolve, reject: reject, notify: notify };
  131. }
  132. /**
  133. * Determines if x is promise-like, i.e. a thenable object
  134. * NOTE: Will return true for *any thenable object*, and isn't truly
  135. * safe, since it may attempt to access the `then` property of x (i.e.
  136. * clever/malicious getters may do weird things)
  137. * @param {*} x anything
  138. * @returns {boolean} true if x is promise-like
  139. */
  140. function isPromiseLike(x) {
  141. return x && typeof x.then === 'function';
  142. }
  143. /**
  144. * Return a promise that will resolve only once all the supplied arguments
  145. * have resolved. The resolution value of the returned promise will be an array
  146. * containing the resolution values of each of the arguments.
  147. * @param {...*} arguments may be a mix of promises and values
  148. * @returns {Promise}
  149. */
  150. function join(/* ...promises */) {
  151. return Promise.all(arguments);
  152. }
  153. /**
  154. * Return a promise that will fulfill once all input promises have
  155. * fulfilled, or reject when any one input promise rejects.
  156. * @param {array|Promise} promises array (or promise for an array) of promises
  157. * @returns {Promise}
  158. */
  159. function all(promises) {
  160. return when(promises, Promise.all);
  161. }
  162. /**
  163. * Return a promise that will always fulfill with an array containing
  164. * the outcome states of all input promises. The returned promise
  165. * will only reject if `promises` itself is a rejected promise.
  166. * @param {array|Promise} promises array (or promise for an array) of promises
  167. * @returns {Promise} promise for array of settled state descriptors
  168. */
  169. function settle(promises) {
  170. return when(promises, Promise.settle);
  171. }
  172. /**
  173. * Promise-aware array map function, similar to `Array.prototype.map()`,
  174. * but input array may contain promises or values.
  175. * @param {Array|Promise} promises array of anything, may contain promises and values
  176. * @param {function(x:*, index:Number):*} mapFunc map function which may
  177. * return a promise or value
  178. * @returns {Promise} promise that will fulfill with an array of mapped values
  179. * or reject if any input promise rejects.
  180. */
  181. function map(promises, mapFunc) {
  182. return when(promises, function(promises) {
  183. return Promise.map(promises, mapFunc);
  184. });
  185. }
  186. /**
  187. * Filter the provided array of promises using the provided predicate. Input may
  188. * contain promises and values
  189. * @param {Array|Promise} promises array of promises and values
  190. * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
  191. * Must return truthy (or promise for truthy) for items to retain.
  192. * @returns {Promise} promise that will fulfill with an array containing all items
  193. * for which predicate returned truthy.
  194. */
  195. function filter(promises, predicate) {
  196. return when(promises, function(promises) {
  197. return Promise.filter(promises, predicate);
  198. });
  199. }
  200. /**
  201. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  202. * input may contain promises and/or values, and reduceFunc
  203. * may return either a value or a promise, *and* initialValue may
  204. * be a promise for the starting value.
  205. * @param {Array|Promise} promises array or promise for an array of anything,
  206. * may contain a mix of promises and values.
  207. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  208. * @returns {Promise} that will resolve to the final reduced value
  209. */
  210. function reduce(promises, f /*, initialValue */) {
  211. /*jshint unused:false*/
  212. var args = slice.call(arguments, 1);
  213. return when(promises, function(array) {
  214. args.unshift(array);
  215. return Promise.reduce.apply(Promise, args);
  216. });
  217. }
  218. /**
  219. * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
  220. * input may contain promises and/or values, and reduceFunc
  221. * may return either a value or a promise, *and* initialValue may
  222. * be a promise for the starting value.
  223. * @param {Array|Promise} promises array or promise for an array of anything,
  224. * may contain a mix of promises and values.
  225. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
  226. * @returns {Promise} that will resolve to the final reduced value
  227. */
  228. function reduceRight(promises, f /*, initialValue */) {
  229. /*jshint unused:false*/
  230. var args = slice.call(arguments, 1);
  231. return when(promises, function(array) {
  232. args.unshift(array);
  233. return Promise.reduceRight.apply(Promise, args);
  234. });
  235. }
  236. return when;
  237. });
  238. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });