Skip to content

Instantly share code, notes, and snippets.

@mihansweatpants
Last active May 3, 2019 21:12
Show Gist options
  • Select an option

  • Save mihansweatpants/18e6cd82255e9582d2ab33a1d6856019 to your computer and use it in GitHub Desktop.

Select an option

Save mihansweatpants/18e6cd82255e9582d2ab33a1d6856019 to your computer and use it in GitHub Desktop.

Go-like error handling

Stole from here 🙂

/* Helper for removing async/await try/catch stuff */
function O_o(promise) {
  return promise.then((data) => {
    if (data instanceof Error) return [data];
    return [null, data];
  }).catch(err => [err]);
}

async function usageExample(params) {
  const [err, data] = await O_o(myPromise(params));

  if (err) {
    // handle or throw err
    throw new Error(err);
  }

  // Do stuff with data
  return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment