diff options
author | elioat <{ID}+{username}@users.noreply.github.com> | 2024-10-16 09:06:08 -0400 |
---|---|---|
committer | elioat <{ID}+{username}@users.noreply.github.com> | 2024-10-16 09:06:08 -0400 |
commit | 241a8c5f3821d36a058aea15faec0dacb14af38c (patch) | |
tree | 818dc7a8d982233c98cdb0c4e944bdc6a2ebf9f7 | |
parent | 4874c88bb126c42563940460ca2637af14ad1823 (diff) | |
download | tour-241a8c5f3821d36a058aea15faec0dacb14af38c.tar.gz |
*
-rw-r--r-- | js/catchError.js | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/js/catchError.js b/js/catchError.js new file mode 100644 index 0000000..0f833ae --- /dev/null +++ b/js/catchError.js @@ -0,0 +1,53 @@ + +// handle errors in async functions without using try/catch +function catchError(promise) { + return promise + .then(data => [undefined, data]) + .catch(error => [error]); +} + + + + + + + + + + + +// Examples + +function examplePromise(success) { + return new Promise((resolve, reject) => { + if (success) { + resolve("Data loaded successfully!"); + } else { + reject("Failed to load data."); + } + }); +} + +async function runExample() { + const [error, data] = await catchError(examplePromise(true)); + + if (error) { + console.error("Error:", error); + } else { + console.log("Success:", data); + } +} + +runExample(); + +async function runExample2() { + const [error, data] = await catchError(examplePromise(false)); + + if (error) { + console.error("Error:", error); + } else { + console.log("Success:", data); + } +} + +runExample2(); \ No newline at end of file |