first.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. define([
  2. "../_base/array",
  3. "../Deferred",
  4. "../when"
  5. ], function(array, Deferred, when){
  6. "use strict";
  7. // module:
  8. // dojo/promise/first
  9. var forEach = array.forEach;
  10. return function first(objectOrArray){
  11. // summary:
  12. // Takes multiple promises and returns a new promise that is fulfilled
  13. // when the first of these promises is fulfilled.
  14. // description:
  15. // Takes multiple promises and returns a new promise that is fulfilled
  16. // when the first of these promises is fulfilled. Canceling the returned
  17. // promise will *not* cancel any passed promises. The promise will be
  18. // fulfilled with the value of the first fulfilled promise.
  19. // objectOrArray: Object|Array?
  20. // The promises are taken from the array or object values. If no value
  21. // is passed, the returned promise is resolved with an undefined value.
  22. // returns: dojo/promise/Promise
  23. var array;
  24. if(objectOrArray instanceof Array){
  25. array = objectOrArray;
  26. }else if(objectOrArray && typeof objectOrArray === "object"){
  27. array = [];
  28. for(var key in objectOrArray){
  29. if(Object.hasOwnProperty.call(objectOrArray, key)){
  30. array.push(objectOrArray[key]);
  31. }
  32. }
  33. }
  34. if(!array || !array.length){
  35. return new Deferred().resolve();
  36. }
  37. var deferred = new Deferred();
  38. forEach(array, function(valueOrPromise){
  39. when(valueOrPromise, deferred.resolve, deferred.reject);
  40. });
  41. return deferred.promise; // dojo/promise/Promise
  42. };
  43. });