-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcb-promise.js
53 lines (48 loc) · 1.11 KB
/
cb-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
const fs = require('fs')
// fs.readFile('./package.json', (err, data) => {
// if (err) return console.log(err)
// data = JSON.parse(data)
// console.log(data.name)
// })
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
}
// readFileAsync('./package.json')
// .then(JSON.parse)
// .then(data => {
// console.log(data.name)
// })
// .catch(err => {
// console.log('err', err)
// })
const { promisify } = require('util')
promisify(fs.readFile)('./package.json', 'utf8')
.then(JSON.parse)
.then(data => {
console.log('data', data.name)
})
.catch(err => {
console.log('err', err)
})
function promiseify(fn) {
return (...rest) =>
new Promise((resolve, reject) => {
fn(...rest, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
}
promiseify(fs.readFile)('./package.json', 'utf8')
.then(JSON.parse)
.then(data => {
console.log('data', data.name)
})
.catch(err => {
console.log('err', err)
})