Node 提供了多个实用工具,使异步代码更清晰、更可控 — 将旧的回调 API 转换为 Promise、取消操作以及协调多个异步任务。
promisify — 将回调 API 转换为 Promise
js
{ promisify } ;
fs ;
readFileAsync = (fs.);
data = (, );
Node 提供了多个实用工具,使异步代码更清晰、更可控 — 将旧的回调 API 转换为 Promise、取消操作以及协调多个异步任务。
{ promisify } ;
fs ;
readFileAsync = (fs.);
data = (, );
promisify 包装任何标准的 (args..., (err, result) => {}) 回调函数,使你可以 await 它 — 对于早期不支持 Promise 的库非常有用。(许多内置模块现在直接提供 Promise 版本,例如 fs/promises。)
const controller = new AbortController();
// pass the signal to a cancellable operation
const promise = fetch("https://api.example.com", { signal: controller.signal });
// cancel it (e.g. on timeout or user navigation)
setTimeout(() => controller.abort(), 5000); // abort after 5s
try {
await promise;
} catch (err) {
if (err.name === "AbortError") console.log("request cancelled");
}
AbortController 提供了一种标准方式来取消进行中的操作(fetch、timers、streams 以及许多库)— 对于超时和在不再需要结果时避免浪费工作至关重要。
// run in parallel, wait for ALL (fails fast if any rejects)
const [a, b, c] = await Promise.all([getA(), getB(), getC()]);
// wait for all, get each result OR error (never short-circuits)
const results = await Promise.allSettled([getA(), getB()]);
// the first to settle (resolve OR reject) wins
const fastest = await Promise.race([fetchPrimary(), fetchBackup()]);
// the first to FULFILL (ignores rejections until one succeeds)
const first = await Promise.any([source1(), source2()]);
这些组合器表达了常见的模式:all 用于并行等待、allSettled 用于不管失败都需要每个结果的情况、race 用于超时/最快赢者、any 用于备用源。
import { setTimeout as sleep } from "timers/promises";
await sleep(1000); // await a delay without wrapping in a Promise manually
这些实用工具使现实世界的异步 Node 代码更清晰、更健壮:promisify 将传统回调 API 桥接到 async/await、AbortController 添加了取消和超时功能(防止悬挂或浪费操作),Promise 组合器(all/allSettled/race/any)简洁且正确地表达了常见的协调模式。
了解这些工具让你可以优雅地处理并行性、取消和回退,而不是重新发明它们 — 这是任何非平凡的异步应用的常见需求。