重试工具
以 尼古拉斯·扎卡斯
如果你觉得有用,请考虑支持我的工作 捐赠 或者说 提名我 为吉他之星.
说明
基于返回错误的 Aync JavaScript 调用失败 .
使用量
节点.js
npm install @humanwhocodes/retry
# or
yarn add @humanwhocodes/retry
导入到您的节点. js 项目 :
// CommonJS
const { Retrier } = require("@humanwhocodes/retry");
// ESM
import { Retrier } from "@humanwhocodes/retry";
德诺
使用 日 尔数字 :
deno add @humanwhocodes/retry
#or
jsr add @humanwhocodes/retry
然后导入您的 Deno 项目 :
import { Retrier } from "@humanwhocodes/retry";
阿宝
使用此命令安装 :
bun add @humanwhocodes/retry
导入您的 Bun 项目 :
import { Retrier } from "@humanwhocodes/retry";
浏览器
建议导入精密版本以节省带宽:
import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry?min";
然而,您也可以导入未修改的版本用于调试:
import { Retrier } from "https://cdn.skypack.dev/@humanwhocodes/retry";
API 密码
导入后创建新实例 Retrier 并指定在错误上运行的函数。 此函数应返回 true 如果你想再打一次电话 false 如果不是的话.
// this instance will retry if the specific error code is found
const retrier = new Retrier(error => {
return error.code === "ENFILE" || error.code === "EMFILE";
});
那么,打电话给 retry() 围绕您想要重试的函数的方法, 例如 :
import fs from "fs/promises";
const retrier = new Retrier(error => {
return error.code === "ENFILE" || error.code === "EMFILE";
});
const text = await retrier.retry(() => fs.readFile("README.md", "utf8"));
这个 retry() 方法要么在成功时通过结果,要么等待并重试失败。 没有被回转器所捕获的任何错误都会被自动拒绝,所以最终的结果是透明地通过成功和失败.
设置超时
您可以控制任务在放弃之前尝试重试的时间 timeout 选项 Retrier 建筑师。 默认时间为一分.
import fs from "fs/promises";
const retrier = new Retrier(error => {
return error.code === "ENFILE" || error.code === "EMFILE";
}, { timeout: 100_000 });
const text = await retrier.retry(() => fs.readFile("README.md", "utf8"));
当调用时, 它拒绝调用函数的第一个错误 .
设定货币限额
当处理大量函数调用时,您可以通过通过 concurrency 选项 Retrier 建筑师。 默认, concurrency 这是1000.
import fs from "fs/promises";
const retrier = new Retrier(error => {
return error.code === "ENFILE" || error.code === "EMFILE";
}, { concurrency: 100 });
const filenames = getFilenames();
const contents = await Promise.all(
filenames.map(filename => retrier.retry(() => fs.readFile(filename, "utf8"))
);
中止为 AbortSignal
也可以通过一个 AbortSignal 取消重试 :
import fs from "fs/promises";
const controller = new AbortController();
const retrier = new Retrier(error => {
return error.code === "ENFILE" || error.code === "EMFILE";
});
const text = await retrier.retry(
() => fs.readFile("README.md", "utf8"),
{ signal: controller.signal }
);
开发者设置
- 叉子存储器
- 砍断你的叉子
- 运行
npm install要设置依赖关系 - 运行
npm test运行测试
除错输出
通过设置调试输出 DEBUG 环境变量改为 "@hwc/retry" 运行前.
许可证
Apache 2.0 (英语)
上一个艺术
此工具的灵感来自, 包含代码来自 graceful-fs。 。 。 .