UNPKG

safety-number-one

Version:

Utility functions to work with Promises, functions and async functions safely by converting throws to Result Tuple types

38 lines 1.89 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { convertUnknownCatchToError } from "convert-unknown-catch-to-error"; /** * Utility function run an async function safely to prevent it from * throwing and returns a `ResultTuple`. * * ### Alternatively * 1. Run a synchronous function with global util `runFnSafely`. * 1. Await a Promise with global util `awaitPromiseSafely`. * * ### Unknown original function return type * Sometimes you want to deal with functions that can be synchronous or async, * i.e. the function return type is not known at compile time. In such cases * choose `runAsyncFnSafely` instead of `runFnSafely` for compatibility. * Because even if a synchronous function is passed in, this will still await * it, which is equivalent to `Promise.resolve(value)`. * However if you do know that the function will be synchronous, prefer * `runFnSafely` for a non `Promise<T>` wrapped return type. */ export function runAsyncFnSafely(fn, ...args) { return __awaiter(this, void 0, void 0, function* () { try { return [null, yield fn(...args)]; } catch (e) { return [convertUnknownCatchToError(e), null]; } }); } //# sourceMappingURL=runAsyncFnSafely.js.map