Skip to main content
On this page

@std/async

Overview Jump to heading

Provide helpers with asynchronous tasks like delays, debouncing, retrying, or pooling.

import { delay } from "@std/async/delay";

await delay(100); // waits for 100 milliseconds

Add to your project Jump to heading

deno add jsr:@std/async

See all symbols in @std/async on

什么是 async? Jump to heading

异步编程允许你的程序现在开始执行任务,稍后完成,而不会阻塞主线程。在 JavaScript 中,这通常表示 Promise、async/await、定时器和异步迭代器。异步代码通过交叉处理 I/O(网络、磁盘、定时器)并控制并发,提高响应性和吞吐量。

为什么使用 @std/async? Jump to heading

这个包为你提供小巧且专注的工具,解决常见的异步问题,避免你重新实现它们:

  • 用于调度和超时的 delaydeadline(支持通过 AbortSignal 取消)。
  • 控制调用频率的 debounce(和不稳定的 throttle),适用于 UI/命令行事件。
  • 带退避和抖动的 retry,用于不稳定的操作比如 HTTP 请求。
  • 用于转换任务流时限制并发的 pooledMap
  • 用于分支或合并异步迭代器的 tee/MuxAsyncIterator

这些辅助工具体积小、行为可预测,且支持 Deno、Node.js、Bun、Workers 和浏览器。

示例 Jump to heading

防抖快速触发的事件(例如自动补全):

import { debounce } from "@std/async/debounce";

const search = debounce(async (q: string) => {
  // 用户停止输入后获取结果
}, 200);

// 多次调用;只有最后一次调用在 200 毫秒后执行
search("d");
search("de");
search("deno");

带指数退避和抖动的重试:

import { retry } from "@std/async/retry";

const data = await retry(() =>
  fetch("/api").then((r) => {
    if (!r.ok) throw new Error("bad status");
    return r.json();
  }), {
  maxAttempts: 5,
  minTimeout: 100,
  multiplier: 2,
  jitter: 0.2,
});

用 pooledMap 限制并发:

import { pooledMap } from "@std/async/pool";

const urls = ["/a", "/b", "/c", "/d"]; // 实际中可能更多
for await (const res of pooledMap(3, urls, (u) => fetch(u))) {
  // 最多同时进行 3 个请求;结果按完成顺序返回
}

截止时间和取消:

import { deadline } from "@std/async/deadline";

await deadline(fetch("/slow"), 1_000); // 1 秒后抛出 DOMException("TimeoutError")

你找到了你需要的东西吗?

编辑此页面
隐私政策