-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorCallback.js
More file actions
86 lines (73 loc) · 1.84 KB
/
Copy patherrorCallback.js
File metadata and controls
86 lines (73 loc) · 1.84 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function doSomethingAsync(callback) {
// Simulate an asynchronous operation
setTimeout(() => {
const hasError = Math.random() > 0.5; // Simulate a 50% chance of error
if (hasError) {
callback(new Error("Something went wrong!"));
} else {
callback(null, "Operation successful!");
}
}, 1000);
}
doSomethingAsync((err, result) => {
if (err) {
console.error("Error:", err.message);
} else {
console.log("Result:", result);
}
});
// callback hell
asyncOperation1((err, result1) => {
if (err) {
/* handle error */
}
asyncOperation2(result1, (err, result2) => {
if (err) {
/* handle error */
}
asyncOperation3(result2, (err, result3) => {
if (err) {
/* handle error */
}
// ... and so on
});
});
});
// error-first callback
import fs from "fs";
// Reading file with callback
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
console.log("File contents:", data);
});
// callback hell
// Problematic nested callbacks
fs.readFile("file1.txt", "utf8", (err1, data1) => {
if (err1) return console.error(err1);
fs.readFile("file2.txt", "utf8", (err2, data2) => {
if (err2) return console.error(err2);
fs.writeFile("output.txt", data1 + data2, (err3) => {
if (err3) return console.error(err3);
console.log("Files combined successfully");
});
});
});
// error-first callback
function asyncOperation(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const error = null; // or some error object if an error occurred
const result = 'Operation completed';
callback(error, result);
}, 1000);
}
asyncOperation((err, result) => {
if (err) {
console.error('An error occurred:', err);
return;
}
console.log('Result:', result);
});