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>;

declare function concurrent<A>(length: number, iterable?: AsyncIterable<A>): (iterable: AsyncIterable<A>) => 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

Open Source Code