forked from yeyan1996/practical-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promisify.js
39 lines (31 loc) · 885 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
// 使用 nodejs 运行以下代码
// 适合err-first风格的异步操作(eg. nodejs)的 promisify 通用函数
const fs = require("fs")
function promisify(asyncFunc) {
return function (...args) {
return new Promise((resolve, reject) => {
args.push(function callback(err, ...values) {
if (err) {
return reject(err);
}
return resolve(...values)
});
asyncFunc.call(this, ...args);
});
};
}
const fsp = new Proxy(fs,{
get(target, key) {
return promisify(target[key])
}
})
async function generateCommit() {
try {
let data = await fsp.readFile('./promisify.js', 'utf-8')
data += `\n//我是注释`
await fsp.writeFile('./promisify.js', data)
} catch (e) {
console.log(e)
}
}
generateCommit()