Created
February 2, 2021 16:38
-
-
Save ahamed/d4c97df92828011001be453de8dbfa7b to your computer and use it in GitHub Desktop.
Run Async function and get result and error without try catch.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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