-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromisify.js
55 lines (50 loc) · 842 Bytes
/
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
50
51
52
53
54
55
const fs = require('fs')
function promisify(reader)
{
return function read(...paths)
{
return Promise.all(paths.map(path =>
new Promise((res, rej) =>
{
reader(path, (err, content) =>
{
if (err)
rej(err)
else
res(content)
})
})
))
}
}
const readFilesPromise = promisify(fs.readFile)
readFilesPromise("file.txt", "file2.txt")
.then((texts) =>
{
console.log('CONTENTS:', texts)
})
.catch((err) =>
{
console.log('ERROR:', err)
})
function readerPromise(path)
{
return new Promise((res, rej) => {
fs.readFile(path, (err, content) =>
{
if (err)
rej(err)
else
res(content)
})
})
}
Promise.all([readerPromise("file.txt"), readerPromise("file2.txt")])
.then((texts) =>
{
console.log('CONTENTS:', texts)
})
.catch((err) =>
{
console.log('ERROR:', err)
})