-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path8-promisify.js
More file actions
44 lines (37 loc) · 1.02 KB
/
8-promisify.js
File metadata and controls
44 lines (37 loc) · 1.02 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
'use strict';
const promisify = (fn) => (...args) => {
const promise = new Promise((resolve, reject) => {
const callback = (err, data) => {
if (err) reject(err);
else resolve(data);
};
fn(...args, callback);
});
return promise;
};
// Usage
const fs = require('node:fs');
const read = promisify(fs.readFile);
const main = async () => {
const fileName = '8-promisify.js';
const data = await read(fileName, 'utf8');
console.log(`File "${fileName}" size: ${data.length}`);
// Call from try/catch block
try {
const data = await read('unknown.file', 'utf8');
console.log(`File size: ${data.length}`);
} catch (error) {
console.error(error.message);
}
// Set default value in promise.catch block
const content = await read('unknown.file').catch((error) => {
console.error(error.message);
return null;
});
// Warning: note that you need additional if-statement
if (content) {
console.log({ content });
console.log(`File size: ${content.size}`);
}
};
main();