diff --git a/packages/backend/src/misc/promise-try.ts b/packages/backend/src/misc/promise-try.ts new file mode 100644 index 0000000000..2b1594b2ee --- /dev/null +++ b/packages/backend/src/misc/promise-try.ts @@ -0,0 +1,34 @@ +/* + * SPDX-FileCopyrightText: hazelnoot and other Sharkey contributors + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { types } from 'node:util'; + +const hasPromiseTry = Reflect.has(globalThis.Promise, 'try'); + +/** + * Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/try + */ +export const promiseTry: PromiseTryFunc = hasPromiseTry ? Promise.try : promiseTryPolyfill; + +/** + * Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in a Promise. + */ +export type PromiseTryFunc = (callbackFn: (...args: U) => T | PromiseLike, ...args: U) => Promise>; + +export function promiseTryPolyfill(callbackFn: (...args: U) => T | PromiseLike, ...args: U): Promise> { + try { + const result = callbackFn(...args); + if (types.isPromise(result)) { + // async return or throw + return result as Promise>; + } + // sync return + return Promise.resolve(result); + } catch (err) { + // sync throw + return Promise.reject(err); + } +} +