es.promise.all-settled.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // `Promise.allSettled` method
  9. // https://tc39.es/ecma262/#sec-promise.allsettled
  10. $({ target: 'Promise', stat: true }, {
  11. allSettled: function allSettled(iterable) {
  12. var C = this;
  13. var capability = newPromiseCapabilityModule.f(C);
  14. var resolve = capability.resolve;
  15. var reject = capability.reject;
  16. var result = perform(function () {
  17. var promiseResolve = aCallable(C.resolve);
  18. var values = [];
  19. var counter = 0;
  20. var remaining = 1;
  21. iterate(iterable, function (promise) {
  22. var index = counter++;
  23. var alreadyCalled = false;
  24. remaining++;
  25. call(promiseResolve, C, promise).then(function (value) {
  26. if (alreadyCalled) return;
  27. alreadyCalled = true;
  28. values[index] = { status: 'fulfilled', value: value };
  29. --remaining || resolve(values);
  30. }, function (error) {
  31. if (alreadyCalled) return;
  32. alreadyCalled = true;
  33. values[index] = { status: 'rejected', reason: error };
  34. --remaining || resolve(values);
  35. });
  36. });
  37. --remaining || resolve(values);
  38. });
  39. if (result.error) reject(result.value);
  40. return capability.promise;
  41. }
  42. });