when.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. define([
  2. "./Deferred",
  3. "./promise/Promise"
  4. ], function(Deferred, Promise){
  5. "use strict";
  6. // module:
  7. // dojo/when
  8. return function when(valueOrPromise, callback, errback, progback){
  9. // summary:
  10. // Transparently applies callbacks to values and/or promises.
  11. // description:
  12. // Accepts promises but also transparently handles non-promises. If no
  13. // callbacks are provided returns a promise, regardless of the initial
  14. // value. Foreign promises are converted.
  15. //
  16. // If callbacks are provided and the initial value is not a promise,
  17. // the callback is executed immediately with no error handling. Returns
  18. // a promise if the initial value is a promise, or the result of the
  19. // callback otherwise.
  20. // valueOrPromise:
  21. // Either a regular value or an object with a `then()` method that
  22. // follows the Promises/A specification.
  23. // callback: Function?
  24. // Callback to be invoked when the promise is resolved, or a non-promise
  25. // is received.
  26. // errback: Function?
  27. // Callback to be invoked when the promise is rejected.
  28. // progback: Function?
  29. // Callback to be invoked when the promise emits a progress update.
  30. // returns: dojo/promise/Promise
  31. // Promise, or if a callback is provided, the result of the callback.
  32. var receivedPromise = valueOrPromise && typeof valueOrPromise.then === "function";
  33. var nativePromise = receivedPromise && valueOrPromise instanceof Promise;
  34. if(!receivedPromise){
  35. if(arguments.length > 1){
  36. return callback ? callback(valueOrPromise) : valueOrPromise;
  37. }else{
  38. return new Deferred().resolve(valueOrPromise);
  39. }
  40. }else if(!nativePromise){
  41. var deferred = new Deferred(valueOrPromise.cancel);
  42. valueOrPromise.then(deferred.resolve, deferred.reject, deferred.progress);
  43. valueOrPromise = deferred.promise;
  44. }
  45. if(callback || errback || progback){
  46. return valueOrPromise.then(callback, errback, progback);
  47. }
  48. return valueOrPromise;
  49. };
  50. });