Skip to content

Instantly share code, notes, and snippets.

@sibizulu
Last active September 28, 2021 03:41
Show Gist options
  • Save sibizulu/0b78f3f328e03dd9dc14f18ca7bfd41d to your computer and use it in GitHub Desktop.
Save sibizulu/0b78f3f328e03dd9dc14f18ca7bfd41d to your computer and use it in GitHub Desktop.

Solution to a better async/await error handling

const requestHandle = (promise) => {
  return promise
    .then(data => ([data, undefined]))
    .catch(error => Promise.resolve([undefined, error]));
}

Example

const exampleMultipleAwait = async () => {
  let [user, userErr] = await requestHandle(getUser());
  if(userErr) throw new Error('Could not fetch user details');

  let [items,itemsErr] = await requestHandle(getItems());
  if(itemsErr) throw new Error('Could not fetch items');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment