You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.2 KiB

4 years ago
  1. "use strict";
  2. module.exports = function(
  3. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  4. var util = require("./util");
  5. var raceLater = function (promise) {
  6. return promise.then(function(array) {
  7. return race(array, promise);
  8. });
  9. };
  10. function race(promises, parent) {
  11. var maybePromise = tryConvertToPromise(promises);
  12. if (maybePromise instanceof Promise) {
  13. return raceLater(maybePromise);
  14. } else {
  15. promises = util.asArray(promises);
  16. if (promises === null)
  17. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  18. }
  19. var ret = new Promise(INTERNAL);
  20. if (parent !== undefined) {
  21. ret._propagateFrom(parent, 3);
  22. }
  23. var fulfill = ret._fulfill;
  24. var reject = ret._reject;
  25. for (var i = 0, len = promises.length; i < len; ++i) {
  26. var val = promises[i];
  27. if (val === undefined && !(i in promises)) {
  28. continue;
  29. }
  30. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  31. }
  32. return ret;
  33. }
  34. Promise.race = function (promises) {
  35. return race(promises, undefined);
  36. };
  37. Promise.prototype.race = function () {
  38. return race(this, undefined);
  39. };
  40. };