Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active January 21, 2023 16:06
Show Gist options
  • Save smitroshin/bd1ffc8a490a08bd50225d69e6c16241 to your computer and use it in GitHub Desktop.
Save smitroshin/bd1ffc8a490a08bd50225d69e6c16241 to your computer and use it in GitHub Desktop.
Async + Await Error Handling Strategy
/**
* Source: https://youtu.be/wsoQ-fgaoyQ
*/
export const asyncHelper = (promise) =>
Promise.allSettled([promise]).then(([{ value, reason }]) => ({
data: value,
error: reason,
}));
// Usage:
// const suc = () => Promise.resolve('success');
// const err = () => Promise.reject('error');
// const { data, error } = await asyncHelper(suc()); // ? { data: 'success', error: undefined }
// const { data, error } = await asyncHelper(err()); // ? { data: undefined, error: 'error' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment