-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart-15-promises.js
74 lines (69 loc) · 1.95 KB
/
part-15-promises.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
const { readFile, writeFile } = require('fs');
// use promise
const getText = (path) => {
return new Promise((resolve, reject) => {
readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
getText('./content/first.txt')
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
// use async await
const start = async() => {
try {
const first = await getText('./content/first.txt');
const second = await getText('./content/second.txt');
console.log(first);
console.log(second);
} catch (error) {
console.log(error);
}
}
start();
// now simplify this down using util
const util = require('util');
const readFilePromise = util.promisify(readFile);
const writeFilePromise = util.promisify(writeFile);
const improvedStart = async() => {
try {
const first = await readFilePromise('./content/first.txt', 'utf8');
const second = await readFilePromise('./content/second.txt', 'utf8');
await writeFilePromise(
'./content/result-part-15.txt',
`Awesome! ${first} ${second}`
)
console.log(first, second);
} catch (error) {
console.log(error);
}
}
improvedStart();
// we can tidy down even more!
const fs = require('fs').promises;
const readFilePr = fs.readFile;
const writeFilePr = fs.writeFile;
const bestStart = async () => {
try {
const first = await readFilePr('./content/first.txt', 'utf8');
const second = await readFilePr('./content/second.txt', 'utf8');
await writeFilePr(
'./content/result-part-15-best.txt',
`This is the best it could possibly be! ${first} ${second}`,
{ flag: 'a' }
)
console.log(first, second);
} catch (error) {
console.log(error);
}
}
bestStart();