ondrain(drainable)


  • drainable <Object> 实现了可排水协议的对象。
  • 返回:<null>

等待可排水写入器的背压清除。当写入器可以接受更多数据时,返回一个解析为 true 的 Promise;如果对象未实现可排水协议,则返回 null

🌐 Wait for a drainable writer's backpressure to clear. Returns a promise that resolves to true when the writer can accept more data, or null if the object does not implement the drainable protocol.

import { push, ondrain, text } from 'node:stream/iter';

const { writer, readable } = push({ highWaterMark: 2 });
writer.writeSync('a');
writer.writeSync('b');

// Start consuming so the buffer can actually drain
const consuming = text(readable);

// Buffer is full -- wait for drain
const canWrite = await ondrain(writer);
if (canWrite) {
  await writer.write('c');
}
await writer.end();
await consuming;const { push, ondrain, text } = require('node:stream/iter');

async function run() {
  const { writer, readable } = push({ highWaterMark: 2 });
  writer.writeSync('a');
  writer.writeSync('b');

  // Start consuming so the buffer can actually drain
  const consuming = text(readable);

  // Buffer is full -- wait for drain
  const canWrite = await ondrain(writer);
  if (canWrite) {
    await writer.write('c');
  }
  await writer.end();
  await consuming;
}

run().catch(console.error);