es.promise.any.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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_ANY_ERROR = 'No one promise resolved';
  10. // `Promise.any` method
  11. // https://tc39.es/ecma262/#sec-promise.any
  12. $({ target: 'Promise', stat: true }, {
  13. any: function any(iterable) {
  14. var C = this;
  15. var AggregateError = getBuiltIn('AggregateError');
  16. var capability = newPromiseCapabilityModule.f(C);
  17. var resolve = capability.resolve;
  18. var reject = capability.reject;
  19. var result = perform(function () {
  20. var promiseResolve = aCallable(C.resolve);
  21. var errors = [];
  22. var counter = 0;
  23. var remaining = 1;
  24. var alreadyResolved = false;
  25. iterate(iterable, function (promise) {
  26. var index = counter++;
  27. var alreadyRejected = false;
  28. remaining++;
  29. call(promiseResolve, C, promise).then(function (value) {
  30. if (alreadyRejected || alreadyResolved) return;
  31. alreadyResolved = true;
  32. resolve(value);
  33. }, function (error) {
  34. if (alreadyRejected || alreadyResolved) return;
  35. alreadyRejected = true;
  36. errors[index] = error;
  37. --remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
  38. });
  39. });
  40. --remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
  41. });
  42. if (result.error) reject(result.value);
  43. return capability.promise;
  44. }
  45. });