实现说明
await 点把异步工作排成序列,拒绝落在取结果的那一行。导入清单标出了平台接触面:finished、PassThrough,全部来自 node:stream/promises、node:stream。
各个操作都建立在顶层绑定之上:sink、chunks、failing。
使用要点
- 无需安装:
node:stream/promises随 Node.js 本体提供。 - 直接运行文件,输出会带上标签,比如
chunks received:、rejected with:——输出的每一行都能指回产生它的那次调用。
常见问题
有第三方依赖吗?
不需要。导入解析到 Node.js 核心模块,运行时自带。
核心语句
await finished(failing).then(
() => console.log("unexpected success"),
(err) => console.log("rejected with:", err.message)
);
process.nextTick(() => failing.destroy(new Error("disk went away")));
sink.on("data", (chunk) => chunks.push(chunk));
代码示例
import { finished } from "node:stream/promises";
import { PassThrough } from "node:stream";
// finished() returns a promise that settles on stream completion or
// rejects on error - pipeline composes streams, finished just waits for one
const sink = new PassThrough();
const chunks = [];
sink.on("data", (chunk) => chunks.push(chunk));
sink.write("alpha\n");
sink.write("beta\n");
sink.end();
await finished(sink);
console.log("chunks received:", chunks.join("").trim().split("\n"));
const failing = new PassThrough();
failing.on("data", () => {});
process.nextTick(() => failing.destroy(new Error("disk went away")));
await finished(failing).then(
() => console.log("unexpected success"),
(err) => console.log("rejected with:", err.message)
);