Skip to content

Commit 9d73e69

Browse files
committed
Improve naive fetch
1 parent 6dc7bb1 commit 9d73e69

File tree

1 file changed

+6
-18
lines changed

1 file changed

+6
-18
lines changed

JavaScript/6-fetch.js

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,16 @@
33
const http = require('node:http');
44

55
const fetch = (url) => new Promise((resolve, reject) => {
6-
http.get(url, (res) => {
6+
http.get(url, async (res) => {
77
const code = res.statusCode;
88
if (code !== 200) {
9-
return void reject(new Error(`HTTP status code ${code}`));
9+
const err = new Error(`HTTP status code ${code}`);
10+
return void reject(err);
1011
}
11-
12-
res.on('error', reject);
13-
1412
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-
return void resolve(object);
24-
} catch (error) {
25-
return void reject(error);
26-
}
27-
});
13+
for await (const chunk of res) chunks.push(chunk);
14+
const data = Buffer.concat(chunks).toString();
15+
resolve(JSON.parse(data));
2816
});
2917
});
3018

0 commit comments

Comments
 (0)