about summary refs log tree commit diff stats
path: root/js/catchError.js
blob: 0f833aef85f66d806988262ad7a7b50fa03ec186 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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();