DEV Community

Discussion on: Go like error handling in TypeScript

Collapse
lukeshiru profile image
LUKESHIRU • Edited

You can achieve something quite simpler without using async/await and Maybe, something like:

const async = <Result>(promise: Promise<Result>) =>
    promise.then(Array.of).catch(error => [, error]) as Promise<
        [result?: Result, error?: unknown]
    >;
Enter fullscreen mode Exit fullscreen mode

And then you can use it like this:

import * as fs from "node:fs/promises";

const main = () =>
    async(fs.readFile("./package.json")).then(([result, error]) => {
        if (!error) {
            console.log(result);
        }
    });

main();
Enter fullscreen mode Exit fullscreen mode

As you mentioned, this is not the best (you can just use Promises normally), but it is a fun "experiment".

Cheers!