-
Notifications
You must be signed in to change notification settings - Fork 3
/
40 async-await example 2.html
86 lines (79 loc) · 2.59 KB
/
40 async-await example 2.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<pre>
https://youtu.be/zCXOR3wBJVA?list=PLt5mNkGuWcuXXFysDLVdCHRh33p9HiGF7
</pre>
<h1></h1>
<script>
//check previous code first
//this code we have taken from code API folder : 9.1 it displays random cat facts
const url = "https://catfact.ninja/fact"; //api we are going to use
const h1 = document.querySelector("h1");
/*
const fetchData = () => {
fetch(url)
.then((response) => response.json())
//.then((data) => h1.innerHTML=data)
.then((data) => (h1.innerHTML = data.fact))
.catch((e) => console.log(e))
.finally(() => console.log("finally done"));
};
fetchData();
*/
//using async-await
/*const fetchData = async () => {
const response = await fetch(url); //here await because it returns promise
const data = await response.json(); // here it also returns promise therefore await here aswell
//console.log(data);
h1.innerHTML = data.fact;
};
fetchData();
*/
/*
console.log("A");
const fetchData = async () => {
console.log("F1");
const response = await fetch(url);
console.log("F2");
const data = await response.json();
console.log("F3");
h1.innerHTML = data.fact; // or //console.log(data);
console.log("F4");
};
fetchData();
console.log("Z");
*/
// o/p : A,F1,Z,F2,F3,F4
// if we use console.log.. in place of h1.innHTML... we get o/p: A,F1,Z,F2,F3,api result,F4
//handling error
/*const fetchData = async () => {
const response = await fetch(url);
const data = await response.json();
h1.innerHTML = data.fact;
};
fetchData().catch((error) => console.log("error: ", error));*/
//handling error using try and catch
const fetchData = async () => {
try {
const response = await fetch(url);
const data = await response.json();
h1.innerHTML = data.fact;
} catch (error) {
document.write("Error: ",error);
//console.log("Error: ",error)
}finally{
console.log("Finally is optional")
}
};
fetchData();
//Note: now its mostly recomended to use try and catch with async-await
</script>
</body>
</html>