readable.some(fn[, options])


稳定性: 1 - 实验

  • fn <Function> | <AsyncFunction> 调用流的每个块的函数。
    • data <any> 来自流的数据块。
    • options <Object>
      • signal <AbortSignal> 如果流被销毁则中止,允许提前中止 fn 调用。
  • options <Object>
    • concurrency <number> 一次调用流的最大并发调用 fn默认值: 1
    • signal <AbortSignal> 如果信号被中止,则允许销毁流。
  • 返回: <Promise> 如果 fn 为至少一个块返回了真值,则为对 true 进行评估的 promise。

此方法类似于 Array.prototype.some,并在流中的每个块上调用 fn,直到等待的返回值为 true(或任何真值)。 一旦对块等待返回值的 fn 调用为真,则流将被销毁,并使用 true 履行 promise。 如果对块的 fn 调用都没有返回真值,则 promise 使用 false 履行。

import { Readable } from 'node:stream';
import { stat } from 'node:fs/promises';

// 使用同步谓词。
await Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true
await Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false

// 使用异步谓词,一次最多进行 2 个文件检查。
const anyBigFile = await Readable.from([
  'file1',
  'file2',
  'file3',
]).some(async (fileName) => {
  const stats = await stat(fileName);
  return stat.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(anyBigFile); // 如果列表中的任何文件大于 1MB,则为 `true`
console.log('done'); // 流已结束

Stability: 1 - Experimental

  • fn <Function> | <AsyncFunction> a function to call on each chunk of the stream.
    • 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.
  • options <Object>
    • concurrency <number> the maximum concurrent invocation of fn to call on the stream at once. Default: 1.
    • signal <AbortSignal> allows destroying the stream if the signal is aborted.
  • Returns: <Promise> a promise evaluating to true if fn returned a truthy value for at least one of the chunks.

This method is similar to Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.

import { Readable } from 'node:stream';
import { stat } from 'node:fs/promises';

// With a synchronous predicate.
await Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true
await Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false

// With an asynchronous predicate, making at most 2 file checks at a time.
const anyBigFile = await Readable.from([
  'file1',
  'file2',
  'file3',
]).some(async (fileName) => {
  const stats = await stat(fileName);
  return stat.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(anyBigFile); // `true` if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished