UNPKG

safety-number-one

Version:

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

55 lines 2.59 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.awaitPromiseSafely = awaitPromiseSafely; const convert_unknown_catch_to_error_1 = require("convert-unknown-catch-to-error"); /** * Utility function await a Promise safely to prevent it from throwing and * returns a `ResultTuple`. * * ### Alternatively * 1. Run a synchronous function with global util `runFnSafely`. * 1. Run an async function with global util `runAsyncFnSafely`. * * ### Important Note * Make sure you do not pass in a synchronous function call like * ```typescript * function test() { * throw new Error('testing'); * } * awaitPromiseSafely(test()); * ``` * This will not work, as it will throw before control flow even passes to * `awaitPromiseSafely`, effectively making this function call useless. * * ## Prefer `runAsyncFnSafely` * The execution starts at the promise creator function's call site, and only * when the first await is found, then the whole thing becomes a Promise and * get passed into this `awaitPromiseSafely` wrapper as its argument, and * execution gets yielded to the await in this function. So potentially, * during the time between calling `awaitPromiseSafely` and creating the * promise, it might have already thrown in a synchronous manner, see the * important note above on how it could happen. Which is why * `runAsyncFnSafely` is a safer alternative since the initial call is * already protected by a try/catch inside `runAsyncFnSafely`, but the * downside being an additional function call stack. */ function awaitPromiseSafely(promise) { return __awaiter(this, void 0, void 0, function* () { try { return [null, yield promise]; } catch (e) { return [(0, convert_unknown_catch_to_error_1.convertUnknownCatchToError)(e), null]; } }); } //# sourceMappingURL=awaitPromiseSafely.js.map