es.promise.all.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var aCallable = require('../internals/a-callable');
  5. var newPromiseCapabilityModule = require('../internals/new-promise-capability');
  6. var perform = require('../internals/perform');
  7. var iterate = require('../internals/iterate');
  8. var PROMISE_STATICS_INCORRECT_ITERATION = require('../internals/promise-statics-incorrect-iteration');
  9. // `Promise.all` method
  10. // https://tc39.es/ecma262/#sec-promise.all
  11. $({ target: 'Promise', stat: true, forced: PROMISE_STATICS_INCORRECT_ITERATION }, {
  12. all: function all(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 = aCallable(C.resolve);
  19. var values = [];
  20. var counter = 0;
  21. var remaining = 1;
  22. iterate(iterable, function (promise) {
  23. var index = counter++;
  24. var alreadyCalled = false;
  25. remaining++;
  26. call($promiseResolve, C, promise).then(function (value) {
  27. if (alreadyCalled) return;
  28. alreadyCalled = true;
  29. values[index] = value;
  30. --remaining || resolve(values);
  31. }, reject);
  32. });
  33. --remaining || resolve(values);
  34. });
  35. if (result.error) reject(result.value);
  36. return capability.promise;
  37. }
  38. });