JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 14597
  • Score
    100M100P100Q136790F
  • License MIT

Package Exports

  • p-safe

Readme

p-safe

Safely handle promise rejections

codecov npm npm bundle size

Install

npm install p-safe

Usage

import { trySafe, type SafeReturn } from 'p-safe';

const { error } = trySafe(async (): SafeReturn<never, Error> => {
  await promiseThatMightReject();
  await fetch('...');
});

if (error) {
  // Handle error
  console.error(error);
  return;
}

console.log(error); // undefined

Or implement your function and only use SafeReturn type:

import type { SafeReturn } from 'p-safe';

async function foo(): Promise<SafeReturn<object, Error>> {
  const resp = await fetch('...');
  if (!resp.ok) {
    return { error: new Error('Request failed for a silly reason') };
  }
  return { data: await resp.json() };
}

const { data, error } = await foo();

if (error) {
  // Handle error
  console.error(error);
  return;
}

console.log(error); // undefined
console.log(data); // { ... }

Are you still confused? Let me explain it in a simple way. p-safe is a simple utility that helps you to safely handle promise rejections. It's a simple and clean way to handle promise rejections without using try/catch blocks.

Check out the tests for more examples.

  • p-catch-if - Conditional promise catch handler
  • p-if - Conditional promise chains
  • p-tap - Tap into a promise chain without affecting its value or state
  • p-log - Log the value/error of a promise
  • More…

License

MIT © Shahrad Elahi