Skip to content

Commit cadb0ed

Browse files
committed
Rewrite examples
1 parent a4dda99 commit cadb0ed

File tree

4 files changed

+48
-48
lines changed

4 files changed

+48
-48
lines changed

JavaScript/4-then.js

-22
This file was deleted.

JavaScript/5-finally.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
5+
const readTextFile = filename => fs.promises.readFile(filename, 'utf8');
6+
7+
readTextFile('file1-.txt')
8+
.then(data => {
9+
console.dir({ file1: data });
10+
})
11+
.catch(reason => {
12+
console.log('Cannot read file1.txt');
13+
console.log(reason);
14+
})
15+
.finally(() => {
16+
console.log('finally');
17+
});

JavaScript/6-fetch.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict';
2+
3+
const http = require('http');
4+
5+
const fetch = url => new Promise((resolve, reject) => {
6+
http.get(url, res => {
7+
const code = res.statusCode;
8+
if (code !== 200) {
9+
return reject(new Error(`HTTP status code ${code}`));
10+
}
11+
12+
res.on('error', reject);
13+
14+
const chunks = [];
15+
res.on('data', chunk => {
16+
chunks.push(chunk);
17+
});
18+
19+
res.on('end', () => {
20+
const json = Buffer.concat(chunks).toString();
21+
try {
22+
const object = JSON.parse(json);
23+
resolve(object);
24+
} catch (error) {
25+
return reject(error);
26+
}
27+
});
28+
});
29+
});
30+
31+
module.exports = fetch;

JavaScript/6-reject.js

-26
This file was deleted.

0 commit comments

Comments
 (0)