Skip to content

Introduce `resultify` function

Latest
Compare
Choose a tag to compare
@wiktor-obrebski wiktor-obrebski released this 22 Dec 12:02
· 2 commits to master since this release

Summary of Changes:

  • introduce new helper function resultify

Detailed Changes:

resultify is a helper function akin to Node.js's utils.promisify.
It modifies the return type of any given function, synchronous or asynchronous, to Result.

Examples:

import { Result, Err, resultify } from 'type-safe-errors';

class FetchFailedError extends Error {
  name = "FetchFailedError" as const;
}

async function fetchDataOrErrorResult () {
  try {
    const res = await fetchRemoteData();
    return res.data;
  } catch (err) {
    console.log(err);
    return Err.of(new FetchFailedError());
  }
};

const fetchRemoteDataAsResult = resultify(fetchDataOrErrorResult);
fetchRemoteDataAsResult()
  .map(data => data)
  .mapErr(FetchFailedError, (err) => console.log(err));