forked from HackYourFuture/Assignments
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
58 lines (53 loc) · 2.22 KB
/
index.js
File metadata and controls
58 lines (53 loc) · 2.22 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
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/blob/main/3-UsingAPIs/Week2/README.md#exercise-1-programmer-fun
1. Complete the function `requestData()` using `fetch()` to make a request to
the url passed to it as an argument. The function should return a promise.
Make sure that the promise is rejected in case of HTTP or network errors.
2. Notice that the function `main()` calls `requestData()`, passing it the url
`https://xkcd.now.sh/?comic=latest`. Try and run the code in the browser and
open the browser's console to inspect the data returned from the request.
3. Next, complete the function `renderImage()` to render an image as an `<img>`
element appended to the document's body, using the data returned from the API.
4. Complete the function `renderError()` to render any errors as an `<h1>`
element appended to the document's body.
5. Refactor the `main()` function to use `async/await`.
6. Test error handling, for instance, by temporarily changing the `.sh` in the
url with `.shx`. There is no server at the modified url, therefore this
should result in a network (DNS) error.
------------------------------------------------------------------------------*/
async function requestData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
throw error;
}
}
// Function to render image
function renderImage(data) {
const img = document.createElement('img');
img.src = data.img;
document.body.appendChild(img);
console.log(data);
}
// Function to render errors
function renderError(error) {
const h1 = document.createElement('h1');
h1.textContent = error.message || error;
document.body.appendChild(h1);
console.log(error);
}
// Refactored main function to use async/await
async function main() {
try{
const data = await requestData('https://xkcd.now.sh/?comic=latest');
renderImage(data);
} catch (error) {
renderError(error);
}
}
window.addEventListener('load', main); window.addEventListener('load', main);