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