about summary refs log tree commit diff stats
path: root/js
diff options
context:
space:
mode:
Diffstat (limited to 'js')
-rw-r--r--js/catchError.js53
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