-
Notifications
You must be signed in to change notification settings - Fork 3
/
39 async-await example.html
87 lines (75 loc) · 2.75 KB
/
39 async-await example.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
87
<!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>
<script>
//here we are fetching data from json file in folder ForFetchAPI / use fake json api
//Example 1
// async function getData() {
// console.log("2");
// const response = await fetch("API/ForFetchAPI/students.json");
// console.log("3");
// const result = await response.json();
// return result;
// }
// console.log("1");
// let a = getData();
// console.log("4");
//check o/p : 1,2,4,promise,3
//printing 1,2,3 etc where used to explain how the flow of code works
//Example 2
//now lets keep the code simple
// async function getData() {
// const response = await fetch("API/ForFetchAPI/students.json");
// const result = await response.json();
// return result;
// }
// let a = getData();
// console.log(a);
// //using then and catch
// getData()
// .then((std) => {
// console.log(std);
// })
// .catch((err) => {
// console.log("error occurred ->", err);
// });
/* Here: we called getData() which is an async function which returns us a promise if promise
is successfully returned, then() is called and in case of error, catch() function is called*/
//Now making the above code more simple and short
/*async function getData() {
//const response = await fetch("ForFetchAPI/students.json");
//const result = await response.json();
//return result;
return (await fetch('API/ForFetchAPI/students.json')).json(); //returns data in json format
}
getData()
.then((std) => {
console.log(std);
})
.catch((err) => {
console.log("error occurred ->", err);
});*/
//now this looks fine, but what about error handing currently we handle errors using catch but
//if we need to call the function multiple times then everytime we need to use catch to avoid it
//we are going to use try and catch inside of async function:
async function getData() {
try {
return (await fetch("API/ForFetchAPI/students.json")).json();
} catch (err) {
console.log("error occurred ->", err);
}
}
getData().then((std) => {
console.log(std);
});
//now we don't need to write catch with then here everytime we call this function we can only use
//then to get the response/result
</script>
</body>
</html>