Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created February 2, 2021 16:38
Show Gist options
  • Select an option

  • Save ahamed/d4c97df92828011001be453de8dbfa7b to your computer and use it in GitHub Desktop.

Select an option

Save ahamed/d4c97df92828011001be453de8dbfa7b to your computer and use it in GitHub Desktop.
Run Async function and get result and error without try catch.
/**
* Run Async function and get the result and the error without using try catch.
*
* @author Sajeeb Ahamed <[email protected]>
*/
const runAsync = (func) => func.then((data) => [data, undefined]).catch((error) => Promise.resolve([undefined, error]));
// A function which will return a promise and throw error
const getData = () => {
return new Promise((_, reject) => {
setTimeout(() => reject('Error message'), 1000);
});
}
async function main() {
// Catch error using try/catch
try {
const res = await getData();
} catch (err) {
console.error(err); // console `Error message`
}
// Catch error using runAsync function
const [data, err] = await runAsync(getData());
console.error(err); // console `Error message`
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment