Skip to content

Commit

Permalink
doc: update stream.reduce concurrency note
Browse files Browse the repository at this point in the history
  • Loading branch information
rluvaton committed Mar 19, 2023
1 parent fbd526b commit 4b92bfd
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions doc/api/stream.md
Expand Up @@ -2501,21 +2501,34 @@ This method calls `fn` on each chunk of the stream in order, passing it the
result from the calculation on the previous element. It returns a promise for
the final value of the reduction.

The reducer function iterates the stream element-by-element which means that
there is no `concurrency` parameter or parallelism. To perform a `reduce`
concurrently, it can be chained to the [`readable.map`][] method.

If no `initial` value is supplied the first chunk of the stream is used as the
initial value. If the stream is empty, the promise is rejected with a
`TypeError` with the `ERR_INVALID_ARGS` code property.

```mjs
import { Readable } from 'node:stream';

const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
return previous + data;
});
console.log(ten); // 10
const totalViews = await Readable.from(videosUrl)
.reduce(async (total, url) => {
const views = await getViewsAsync(url);
return total + views;
}, 0);

console.log(totalViews);
```

The reducer function iterates the stream element-by-element which means that
there is no `concurrency` parameter or parallelism. To perform a `reduce`
concurrently, you can extract the async function to [`readable.map`][] method.

```mjs
import { Readable } from 'node:stream';

const totalViews = await Readable.from(videosUrl)
.map((url) => getViewsAsync(url), { concurrency: 2 })
.reduce((total, views) => total + views);

console.log(totalViews);
```

### Duplex and transform streams
Expand Down

0 comments on commit 4b92bfd

Please sign in to comment.