esnext.promise.any.js 1.6 KB

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