Skip to content

Instantly share code, notes, and snippets.

@antklim
Last active September 30, 2022 23:56
Show Gist options
  • Save antklim/91e5b0bd82fae368c9f24a720f0cdc7d to your computer and use it in GitHub Desktop.
Save antklim/91e5b0bd82fae368c9f24a720f0cdc7d to your computer and use it in GitHub Desktop.
type PromiseFunc = (...args: any[]) => Promise<any>;
type TryCatch<Func extends PromiseFunc> = (
...args: [...Parameters<Func>]
) => Promise<[Error | null, Awaited<ReturnType<Func>> | null]>;
const trycatch =
<Func extends PromiseFunc>(f: Func): TryCatch<Func> => async (...args) => {
try {
const v = await f(...args);
return [null, v]
} catch (err) {
return [err as Error, null];
}
};
const main = async () => {
const file = Deno.env.get("FILE");
if (!file) {
console.log("file name required.");
return;
}
console.log(`reading ${file} ...`);
const [err, text] = await trycatch(Deno.readTextFile)(file);
if (err !== null) {
console.error(`failed to read ${file}: ${err}`);
return;
}
console.log(`file content:\n${text}`);
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment