when.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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.4
  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 apply = require('./lib/apply')(Promise);
  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 = lift(Promise.reduce); // Array.reduce() for promises
  45. when.reduceRight = lift(Promise.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, onProgress) {
  67. var p = Promise.resolve(x);
  68. if (arguments.length < 2) {
  69. return p;
  70. }
  71. return p.then(onFulfilled, onRejected, onProgress);
  72. }
  73. /**
  74. * Creates a new promise whose fate is determined by resolver.
  75. * @param {function} resolver function(resolve, reject, notify)
  76. * @returns {Promise} promise whose fate is determine by resolver
  77. */
  78. function promise(resolver) {
  79. return new Promise(resolver);
  80. }
  81. /**
  82. * Lift the supplied function, creating a version of f that returns
  83. * promises, and accepts promises as arguments.
  84. * @param {function} f
  85. * @returns {Function} version of f that returns promises
  86. */
  87. function lift(f) {
  88. return function() {
  89. for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
  90. a[i] = arguments[i];
  91. }
  92. return apply(f, this, a);
  93. };
  94. }
  95. /**
  96. * Call f in a future turn, with the supplied args, and return a promise
  97. * for the result.
  98. * @param {function} f
  99. * @returns {Promise}
  100. */
  101. function attempt(f /*, args... */) {
  102. /*jshint validthis:true */
  103. for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
  104. a[i] = arguments[i+1];
  105. }
  106. return apply(f, this, a);
  107. }
  108. /**
  109. * Creates a {promise, resolver} pair, either or both of which
  110. * may be given out safely to consumers.
  111. * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
  112. */
  113. function defer() {
  114. return new Deferred();
  115. }
  116. function Deferred() {
  117. var p = Promise._defer();
  118. function resolve(x) { p._handler.resolve(x); }
  119. function reject(x) { p._handler.reject(x); }
  120. function notify(x) { p._handler.notify(x); }
  121. this.promise = p;
  122. this.resolve = resolve;
  123. this.reject = reject;
  124. this.notify = notify;
  125. this.resolver = { resolve: resolve, reject: reject, notify: notify };
  126. }
  127. /**
  128. * Determines if x is promise-like, i.e. a thenable object
  129. * NOTE: Will return true for *any thenable object*, and isn't truly
  130. * safe, since it may attempt to access the `then` property of x (i.e.
  131. * clever/malicious getters may do weird things)
  132. * @param {*} x anything
  133. * @returns {boolean} true if x is promise-like
  134. */
  135. function isPromiseLike(x) {
  136. return x && typeof x.then === 'function';
  137. }
  138. /**
  139. * Return a promise that will resolve only once all the supplied arguments
  140. * have resolved. The resolution value of the returned promise will be an array
  141. * containing the resolution values of each of the arguments.
  142. * @param {...*} arguments may be a mix of promises and values
  143. * @returns {Promise}
  144. */
  145. function join(/* ...promises */) {
  146. return Promise.all(arguments);
  147. }
  148. /**
  149. * Return a promise that will fulfill once all input promises have
  150. * fulfilled, or reject when any one input promise rejects.
  151. * @param {array|Promise} promises array (or promise for an array) of promises
  152. * @returns {Promise}
  153. */
  154. function all(promises) {
  155. return when(promises, Promise.all);
  156. }
  157. /**
  158. * Return a promise that will always fulfill with an array containing
  159. * the outcome states of all input promises. The returned promise
  160. * will only reject if `promises` itself is a rejected promise.
  161. * @param {array|Promise} promises array (or promise for an array) of promises
  162. * @returns {Promise} promise for array of settled state descriptors
  163. */
  164. function settle(promises) {
  165. return when(promises, Promise.settle);
  166. }
  167. /**
  168. * Promise-aware array map function, similar to `Array.prototype.map()`,
  169. * but input array may contain promises or values.
  170. * @param {Array|Promise} promises array of anything, may contain promises and values
  171. * @param {function(x:*, index:Number):*} mapFunc map function which may
  172. * return a promise or value
  173. * @returns {Promise} promise that will fulfill with an array of mapped values
  174. * or reject if any input promise rejects.
  175. */
  176. function map(promises, mapFunc) {
  177. return when(promises, function(promises) {
  178. return Promise.map(promises, mapFunc);
  179. });
  180. }
  181. /**
  182. * Filter the provided array of promises using the provided predicate. Input may
  183. * contain promises and values
  184. * @param {Array|Promise} promises array of promises and values
  185. * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
  186. * Must return truthy (or promise for truthy) for items to retain.
  187. * @returns {Promise} promise that will fulfill with an array containing all items
  188. * for which predicate returned truthy.
  189. */
  190. function filter(promises, predicate) {
  191. return when(promises, function(promises) {
  192. return Promise.filter(promises, predicate);
  193. });
  194. }
  195. return when;
  196. });
  197. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });