array-from-async.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var bind = require('../internals/function-bind-context');
  3. var toObject = require('../internals/to-object');
  4. var isConstructor = require('../internals/is-constructor');
  5. var getAsyncIterator = require('../internals/get-async-iterator');
  6. var getIterator = require('../internals/get-iterator');
  7. var getIteratorMethod = require('../internals/get-iterator-method');
  8. var getMethod = require('../internals/get-method');
  9. var getVirtual = require('../internals/entry-virtual');
  10. var getBuiltIn = require('../internals/get-built-in');
  11. var wellKnownSymbol = require('../internals/well-known-symbol');
  12. var AsyncFromSyncIterator = require('../internals/async-from-sync-iterator');
  13. var toArray = require('../internals/async-iterator-iteration').toArray;
  14. var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator');
  15. var arrayIterator = getVirtual('Array').values;
  16. // `Array.fromAsync` method implementation
  17. // https://github.com/tc39/proposal-array-from-async
  18. module.exports = function fromAsync(asyncItems /* , mapfn = undefined, thisArg = undefined */) {
  19. var C = this;
  20. var argumentsLength = arguments.length;
  21. var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
  22. var thisArg = argumentsLength > 2 ? arguments[2] : undefined;
  23. return new (getBuiltIn('Promise'))(function (resolve) {
  24. var O = toObject(asyncItems);
  25. if (mapfn !== undefined) mapfn = bind(mapfn, thisArg);
  26. var usingAsyncIterator = getMethod(O, ASYNC_ITERATOR);
  27. var usingSyncIterator = usingAsyncIterator ? undefined : getIteratorMethod(O) || arrayIterator;
  28. var A = isConstructor(C) ? new C() : [];
  29. var iterator = usingAsyncIterator
  30. ? getAsyncIterator(O, usingAsyncIterator)
  31. : new AsyncFromSyncIterator(getIterator(O, usingSyncIterator));
  32. resolve(toArray(iterator, mapfn, A));
  33. });
  34. };