-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
86 lines (80 loc) · 2.46 KB
/
promise.js
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
"use strict";
const fs = require("fs");
function promisifiedReadFile(...args) {
return new Promise((resolve, reject) => {
const file = args[0];
console.log(`promisifiedReadFile invoked for: ${file}`);
fs.readFile(...args, (err, value) => {
if (err) {
console.log(`fs.readFile failed for: ${file}. Promise rejected.`);
return reject(err);
}
console.log(`fs.readFile succeeded for: ${file}. Promise fulfilled.`);
resolve(value);
console.log(`fs.readFile succeeded for: ${file}. After resolve.`);
});
});
}
promisifiedReadFile("promise.js", "utf8")
.then((value) => {
console.log("In Then block onFulfilled handler of fulfilled promise ...");
console.log(`File header: ${value.substr(0, 13)}`);
})
.finally(() => {
console.log("In Finally block of fulfilled promise.\n");
});
promisifiedReadFile("no-file-for-then-onRejected")
.then(
(value) => {
// NOTE: This block will not run as the promise is rejected
console.log("In Then block onFulfilled handler of rejected promise ...");
console.log("Value:");
console.log(value);
},
(err) => {
console.log("In Then block onRejection handler of rejected promise ...");
console.log("Error:");
console.log(err);
}
)
.finally(() => {
console.log("In Finally block of rejected promise, following Then.\n");
});
promisifiedReadFile("no-file-for-catch")
.catch((err) => {
console.log("In Catch block of rejected promise ...");
console.log("Error:");
console.log(err);
})
.finally(() => {
console.log("In Finally block of rejected promise, following Catch.\n");
});
promisifiedReadFile("no-file-for-then-catch")
.then(
(value) => {
// NOTE: This block will not run as the promise is rejected
console.log(
"In Then block onFulfilled handler of rejected promise (with Catch) ..."
);
console.log("Value:");
console.log(value);
},
(err) => {
console.log(
"In Then block onRejection handler of rejected promise (with Catch) ..."
);
console.log("Error:");
console.log(err);
}
)
.catch((err) => {
// NOTE: This block will not run as Then block has onRejected handler
console.log("In Catch block of rejected promise, following Then.");
console.log("Error:");
console.log(err);
})
.finally(() => {
console.log(
"In Finally block of rejected promise, following Then & Catch.\n"
);
});