defer
延迟工作直到异步函数完成
415 bytes
since v12.1.0
使用方法
defer 函数允许您在运行异步函数的同时注册清理函数,这些清理函数将在主函数完成后执行。这在您需要清理资源时很有用,无论主函数成功还是失败,类似于 finally 块。
传递给 defer 的函数接收一个 register 函数作为其参数。使用它来注册应在主函数完成后运行的清理工作。
默认情况下,如果清理函数在主函数已抛出错误后抛出错误,清理错误将被忽略。您可以通过向 register 函数传递 { rethrow: true } 来自定义此行为,让它重新抛出清理错误。
清理临时文件
import * as _ from "radashi";
// 占位函数const createBuildDir = async () => { console.log("Creating build directory..."); await _.sleep(100); console.log("Build directory created."); return "build";};const build = async () => { console.log("Building project..."); await _.sleep(100); console.log("Project built.");};
await _.defer(async (cleanup) => { const buildDir = await createBuildDir();
cleanup(() => fs.unlink(buildDir));
await build();});在 API 中清理资源
// 占位APIconst api = { org: { create: async () => ({ id: 1 }), delete: async () => { console.log("Deleting organization..."); await _.sleep(100); console.log("Deleted organization."); }, }, user: { create: async () => ({ id: 2 }), delete: async () => { console.log("Deleting user..."); await _.sleep(100); console.log("Deleted user."); }, },};
// 占位测试函数const executeTest = async () => { console.log("Executing test..."); await _.sleep(100); console.log("Test complete.");};
await _.defer(async (register) => { const org = await api.org.create(); register(async () => api.org.delete(org.id), { rethrow: true });
const user = await api.user.create(); register(async () => api.user.delete(user.id), { rethrow: true });
await executeTest(org, user);});