es.promise.any.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var aCallable = require('../internals/a-callable');
  5. var getBuiltIn = require('../internals/get-built-in');
  6. var newPromiseCapabilityModule = require('../internals/new-promise-capability');
  7. var perform = require('../internals/perform');
  8. var iterate = require('../internals/iterate');
  9. var PROMISE_STATICS_INCORRECT_ITERATION = require('../internals/promise-statics-incorrect-iteration');
  10. var PROMISE_ANY_ERROR = 'No one promise resolved';
  11. // `Promise.any` method
  12. // https://tc39.es/ecma262/#sec-promise.any
  13. $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
  14. any: function any(iterable) {
  15. var C = this;
  16. var AggregateError = getBuiltIn('AggregateError');
  17. var capability = newPromiseCapabilityModule.f(C);
  18. var resolve = capability.resolve;
  19. var reject = capability.reject;
  20. var result = perform(function () {
  21. var promiseResolve = aCallable(C.resolve);
  22. var errors = [];
  23. var counter = 0;
  24. var remaining = 1;
  25. var alreadyResolved = false;
  26. iterate(iterable, function (promise) {
  27. var index = counter++;
  28. var alreadyRejected = false;
  29. remaining++;
  30. call(promiseResolve, C, promise).then(function (value) {
  31. if (alreadyRejected || alreadyResolved) return;
  32. alreadyResolved = true;
  33. resolve(value);
  34. }, function (error) {
  35. if (alreadyRejected || alreadyResolved) return;
  36. alreadyRejected = true;
  37. errors[index] = error;
  38. --remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
  39. });
  40. });
  41. --remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
  42. });
  43. if (result.error) reject(result.value);
  44. return capability.promise;
  45. }
  46. });