readable.reduce(fn[, initial[, options]])


稳定性: 1 - 实验

  • fn <Function> | <AsyncFunction> 调用流中每个块的减数函数。
    • previous <any> 从最后一次调用 fn 获得的值或 initial 值(如果指定)或流的第一个块。
    • data <any> 来自流的数据块。
    • options <Object>
      • signal <AbortSignal> 如果流被销毁则中止,允许提前中止 fn 调用。
  • initial <any> 在减数中使用的初始值。
  • options <Object>
    • signal <AbortSignal> 如果信号被中止,则允许销毁流。
  • 返回: <Promise> 用于减数最终值的 promise。

此方法按顺序在流的每个块上调用 fn,并将对前一个元素的计算结果传给它。 它返回减数最终值的 promise。

减数函数逐个元素地迭代流,这意味着没有 concurrency 参数或并行性。 要同时执行 reduce,则可以链接到 readable.map 方法。

如果没有提供 initial 值,则将流的第一个块用作初始值。 如果流为空,则使用带有 ERR_INVALID_ARGS 代码属性的 TypeError 拒绝 promise。

import { Readable } from 'node:stream';

const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
  return previous + data;
});
console.log(ten); // 10

Stability: 1 - Experimental

  • fn <Function> | <AsyncFunction> a reducer function to call over every chunk in the stream.
    • previous <any> the value obtained from the last call to fn or the initial value if specified or the first chunk of the stream otherwise.
    • data <any> a chunk of data from the stream.
    • options <Object>
      • signal <AbortSignal> aborted if the stream is destroyed allowing to abort the fn call early.
  • initial <any> the initial value to use in the reduction.
  • options <Object>
    • signal <AbortSignal> allows destroying the stream if the signal is aborted.
  • Returns: <Promise> a promise for the final value of the reduction.

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.

import { Readable } from 'node:stream';

const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
  return previous + data;
});
console.log(ten); // 10