array-from-async.js 2.2 KB

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