实现说明
镜像的异步回退链的核心是函数 fetchWithFallback、main。
for (const [name, fetchOne] of mirrors) 是唯一的迭代点——其余代码顺序执行一遍。异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。
返回值是携带 true、name 的对象。
使用要点
- 直接运行文件,输出会带上标签,比如
all mirrors failed:、served by:——输出的每一行都能指回产生它的那次调用。
常见问题
fetchWithFallback 会修改传入的参数吗?
没有原地修改——函数读取输入并返回新值。
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 文件在加载时定义 fetchWithFallback、main。
签名一览:async function fetchWithFallback(mirrors: readonly Mirror[], path: string)
核心语句
type Mirror = readonly [name: string, fetchOne: (path: string) => Promise<string>];
return { ok: true, mirror: name, body: await fetchOne(path) };
main().catch((error: unknown) => {
throw error;
});
代码示例
// Result-shaped fallback chain over mirrors: try each in order, the first
// success wins, and every failure is recorded for the final report
type Mirror = readonly [name: string, fetchOne: (path: string) => Promise<string>];
type ChainResult =
| { readonly ok: true; readonly mirror: string; readonly body: string }
| { readonly ok: false; readonly attempts: readonly string[] };
async function fetchWithFallback(mirrors: readonly Mirror[], path: string): Promise<ChainResult> {
const attempts: string[] = [];
for (const [name, fetchOne] of mirrors) {
try {
return { ok: true, mirror: name, body: await fetchOne(path) };
} catch (error) {
attempts.push(`${name}: ${(error as Error).message}`);
}
}
return { ok: false, attempts };
}
// Local stand-ins keep the chain runnable without a network
const mirrors: readonly Mirror[] = [
["eu-1", () => Promise.reject(new Error("503"))],
["us-2", () => Promise.reject(new Error("timeout"))],
["ap-3", (path) => Promise.resolve(`${path} via ap-3`)],
];
async function main(): Promise<void> {
const lost = await fetchWithFallback(mirrors.slice(0, 2), "/v1/status");
console.log("all mirrors failed:", lost.ok ? "unexpected" : lost.attempts);
const won = await fetchWithFallback(mirrors, "/v1/status");
console.log("served by:", won.ok ? won.mirror : "unexpected", "| body:", won.ok ? won.body : "-");
}
main().catch((error: unknown) => {
throw error;
});