Repository navigation
Expand file tree
/
Copy pathXMLHTTPRequest02.js
More file actions
93 lines (74 loc) · 2 KB
/
Copy pathXMLHTTPRequest02.js
File metadata and controls
93 lines (74 loc) · 2 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*Get a User's Posts
You are given two API endpoints:
https://jsonplaceholder.typicode.com/users/{userId}
https://jsonplaceholder.typicode.com/posts?userId={userId}
Create these two functions:
1. getUser(userId)
Use XMLHttpRequest and return a Promise.
It should:
Make a GET request.
Resolve with the parsed user object.
Reject on an unsuccessful HTTP status.
Reject on a network error.
2. getUserPosts(userId)
Use XMLHttpRequest and return a Promise.
It should:
Make a GET request for the user's posts.
Resolve with the parsed array.
Reject on HTTP/network errors.
Then create:
async function main() {
// your code
}
It should:
Get user 5.
Print the user's name.
Get that user's posts.
Print how many posts they have.
Use try...catch to handle errors.*/
//solution
function getUser(userId) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", `https://jsonplaceholder.typicode.com/users/${userId}`);
xhr.onload = function () {
if (!(xhr.status >= 200 && xhr.status < 300))
return reject(new Error(`HTTP Error ${xhr.status}`));
resolve(JSON.parse(xhr.responseText));
};
xhr.onerror = function () {
return reject(new Error(`Network Error`));
};
xhr.send();
});
}
function getUserPosts(userId) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(
"GET",
`https://jsonplaceholder.typicode.com/posts?userId=${userId}`,
);
xhr.onload = function () {
if (!(xhr.status >= 200 && xhr.status < 300)) {
return reject(new Error(`HTTP Error: ${xhr.status}`));
}
resolve(JSON.parse(xhr.responseText));
};
xhr.onerror = function () {
return reject(new Error(`Network Error`));
};
xhr.send();
});
}
async function main() {
try {
const user = await getUser(5);
console.log(user.name);
const posts = await getUserPosts(5);
console.log(posts.length);
} catch (error) {
console.log(error.message);
}
}
main();