es.promise.all-settled.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var aFunction = require('../internals/a-function');
  4. var newPromiseCapabilityModule = require('../internals/new-promise-capability');
  5. var perform = require('../internals/perform');
  6. var iterate = require('../internals/iterate');
  7. // `Promise.allSettled` method
  8. // https://tc39.es/ecma262/#sec-promise.allsettled
  9. $({ target: 'Promise', stat: true }, {
  10. allSettled: function allSettled(iterable) {
  11. var C = this;
  12. var capability = newPromiseCapabilityModule.f(C);
  13. var resolve = capability.resolve;
  14. var reject = capability.reject;
  15. var result = perform(function () {
  16. var promiseResolve = aFunction(C.resolve);
  17. var values = [];
  18. var counter = 0;
  19. var remaining = 1;
  20. iterate(iterable, function (promise) {
  21. var index = counter++;
  22. var alreadyCalled = false;
  23. values.push(undefined);
  24. remaining++;
  25. promiseResolve.call(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. });