UNPKG

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