readable.every(fn[, options])
稳定性: 1 - 实验性
fn<Function> | <AsyncFunction> 是一个在流的每个数据块上调用的函数。data<any> 从流中获取一块数据。options<Object>signal<AbortSignal> 如果流被销毁则中止,从而允许提前中止fn调用。
options<Object>concurrency<number> 是fn在流上同时调用的最大并发次数。默认值:1。signal<AbortSignal> 允许在信号被中止时销毁流。
- 返回值:<Promise> 一个 promise,当
fn对所有块返回了真值时,该 promise 的结果为true。
该方法类似于 Array.prototype.every,会在流中的每个块上调用 fn,以检查所有等待的返回值是否为 fn 的真值。一旦对某个块的 fn 调用返回的等待值为假,流将被销毁,并且该 Promise 会以 false 作为结果。如果所有块上的 fn 调用都返回真值,则该 Promise 会以 true 作为结果。
【This method is similar to Array.prototype.every and calls fn on each chunk
in the stream to check if all awaited return values are truthy value for fn.
Once an fn call on a chunk awaited return value is falsy, the stream is
destroyed and the promise is fulfilled with false. If all of the fn calls
on the chunks return a truthy value, the promise is fulfilled with true.】
import { Readable } from 'node:stream';
import { stat } from 'node:fs/promises';
// With a synchronous predicate.
await Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false
await Readable.from([1, 2, 3, 4]).every((x) => x > 0); // true
// With an asynchronous predicate, making at most 2 file checks at a time.
const allBigFiles = await Readable.from([
'file1',
'file2',
'file3',
]).every(async (fileName) => {
const stats = await stat(fileName);
return stats.size > 1024 * 1024;
}, { concurrency: 2 });
// `true` if all files in the list are bigger than 1MiB
console.log(allBigFiles);
console.log('done'); // Stream has finished