-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path3-promisify.js
49 lines (42 loc) · 1.02 KB
/
3-promisify.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
'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);
});