to.ts 588 B

123456789101112131415161718192021
  1. /**
  2. * @param { Readonly<Promise> } promise
  3. * @param {object=} errorExt - Additional Information you can pass to the err object
  4. * @return { Promise }
  5. */
  6. export async function to<T, U = Error>(
  7. promise: Readonly<Promise<T>>,
  8. errorExt?: object,
  9. ): Promise<[null, T] | [U, undefined]> {
  10. try {
  11. const data = await promise;
  12. const result: [null, T] = [null, data];
  13. return result;
  14. } catch (error) {
  15. if (errorExt) {
  16. const parsedError = Object.assign({}, error, errorExt);
  17. return [parsedError as U, undefined];
  18. }
  19. return [error as U, undefined];
  20. }
  21. }