-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path3-promisify.js
More file actions
52 lines (45 loc) · 1.05 KB
/
3-promisify.js
File metadata and controls
52 lines (45 loc) · 1.05 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
'use strict';
const promisify =
(fn) =>
(...args) =>
new Promise((resolve, reject) => {
args.push((err, result) => {
if (err) reject(err);
else resolve(result);
});
fn(...args);
});
const fs = require('node:fs');
const readFile1 = promisify(fs.readFile);
readFile1('file1.txt', 'utf8')
.then((data) => {
console.log(data.toString());
return readFile1('file2.txt', 'utf8');
})
.then((data) => {
console.log(data.toString());
return readFile1('file3.txt', 'utf8');
})
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.log(err);
});
const util = require('node:util');
const readFile2 = util.promisify(fs.readFile);
readFile2('file1.txt', 'utf8')
.then((data) => {
console.log(data.toString());
return readFile2('file2.txt', 'utf8');
})
.then((data) => {
console.log(data.toString());
return readFile2('file3.txt', 'utf8');
})
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.log(err);
});