Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Last active October 19, 2022 23:43
Show Gist options
  • Save karlhorky/3593d8cd9779cf9313f9852c59260642 to your computer and use it in GitHub Desktop.
Save karlhorky/3593d8cd9779cf9313f9852c59260642 to your computer and use it in GitHub Desktop.
Try-catch helper for promises and async/await
export default async function tryCatch<Data>(
promise: Promise<Data>,
): Promise<{ error: Error } | { data: Data }> {
try {
return { data: await promise };
} catch (error) {
return { error };
}
}
@karlhorky
Copy link
Author

Thanks, I enjoyed the journey too! 🙌

@syed-ahmad
Copy link

Hi @karlhorky, is it okay if I create an npm package for that with tests?

@karlhorky
Copy link
Author

karlhorky commented Jun 29, 2021

TS 4.4 may no longer "forget" the type information after destructuring: https://twitter.com/sebastienlorber/status/1409543348461965314?s=19

@karlhorky
Copy link
Author

Ok, this is true for a single variable, but it doesn't apply for multiple variables being destructured: https://stackoverflow.com/a/59786171/1268612

@karlhorky
Copy link
Author

It looks like this is actually a separate feature request called "Correlated Unions" by jcalz here: microsoft/TypeScript#30581

@karlhorky
Copy link
Author

Seems like this may be in TypeScript 4.6, since this PR got merged:

microsoft/TypeScript#46266

@syed-ahmad
Copy link

Thanks @karlhorky

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment