Skip to main content

concurrent

concurrent() function

Concurrent is used to balance the load of multiple asynchronous requests. The first argument receives a number that controls the number of loads, and the second argument is an AsyncIterable. See toAsync to create an AsyncIterable .

Signature:

declare function concurrent<A>(length: number, iterable: AsyncIterable<A>): AsyncIterableIterator<A>;

Returns:

AsyncIterableIterator<A>

Example

await pipe(
[1, 2, 3, 4, 5, 6],
toAsync,
map((a) => delay(1000, a)),
concurrent(3),
each(console.log), // log 1, 2, 3, 4, 5, 6
); // 2 seconds

// evaluation
// โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”
// โ”‚ 1 โ”‚โ”€โ”€โ”‚ 2 โ”‚โ”€โ”€โ”‚ 3 โ”‚โ”€โ”€โ”‚ 4 โ”‚โ”€โ”€โ”‚ 5 โ”‚โ”€โ”€โ”‚ 6 โ”‚
// โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜
// map โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
// concurrent(3) (1) (1) (1) (2) (2) (2)
// โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
// โ–ผ โ–ผ โ–ผ โ–ผ โ–ผ โ–ผ

await pipe(
[1, 2, 3, 4, 5, 6],
toAsync,
map((a) => delay(1000, a)),
each(console.log), // log 1, 2, 3, 4, 5, 6
); // 6 seconds

// evaluation
// โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”
// โ”‚ 1 โ”‚โ”€โ”€โ”‚ 2 โ”‚โ”€โ”€โ”‚ 3 โ”‚โ”€โ”€โ”‚ 4 โ”‚โ”€โ”€โ”‚ 5 โ”‚โ”€โ”€โ”‚ 6 โ”‚
// โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜ โ””โ”€โ”€โ”ฌโ”€โ”€โ”˜
// map โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
// (1) (2) (3) (4) (5) (6)
// โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
// โ–ผ โ–ผ โ–ผ โ–ผ โ–ผ โ–ผ

Try It

see pipe, toAsync, toArray each, map