-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript.js
More file actions
42 lines (34 loc) · 1.43 KB
/
Copy pathscript.js
File metadata and controls
42 lines (34 loc) · 1.43 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
// Helper functions
// for of over a string
const drawLine = () => console.log("------------------------------------")
const appliedOver = (inp) => {
console.log(`${inp}: `)
}
const spacePeople = () => {
return new Promise((resolves, rejects) => {
// link to api - data source
const api = "http://api.open-notify.org/astros.json"
// build a request
const request = new XMLHttpRequest();
// send GET request to ask data from the API
request.open("GET", api);
// if status is 200 means data received properly and we parse it
request.onload = () => {
if (request.status === 200) {
resolves(JSON.parse(request.response));
} else {
// if status is something non 200, return the statusText
rejects(Error(request.statusText));
}
}
// Say on error rejects with err data
request.onerror = (err) => rejects(err)
request.send(); // send the request
});
};
// The above can be used as boiler plate for any kind of request
// call spacePeople() and then console log the data to our console.
spacePeople().then((spaceData) => {
console.log(spaceData)
}).catch((err) => console.log(new Error("Can't load people.", err)))
// ✅ we call the spacePeople() and use .then() to get the resolves logic and console.log if .then() is not working we do console.log() of err using .catch()