You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// // Here we have to use both .then() and .catch() because otherwise the promise will only get the resovle data and not the reject data if something gets wrong.
22
+
23
+
//$ New ES6 way of writing promises or api calls with async and await methods
// const response = await promise; // or await fetch(url)
29
+
// console.log(response);
30
+
// } catch (err) {
31
+
// console.log(err);
32
+
// }
33
+
// };
34
+
35
+
// fetchData(); // calling the function to fetch data.
36
+
37
+
//@ Advanced or Different way of writing async and await methods
38
+
39
+
//@ Note: In this code, we are using async/await to handle promises. It makes the code cleaner and easier to read. But keep in mind that async/await can only be used in async functions, not regular functions.
40
+
41
+
// async function fetchData() {
42
+
// try {
43
+
// const response = await promise; // or await fetch(url)
44
+
// console.log(response);
45
+
// } catch (err) {
46
+
// console.log(err);
47
+
// }
48
+
// }
49
+
50
+
// fetchData(); // calling the function to fetch data.
51
+
52
+
//! How to get data from a async function
53
+
54
+
letdata={
55
+
rating: undefined,
56
+
tip: undefined,
57
+
pay: undefined,
58
+
review: undefined,
59
+
};
60
+
61
+
constfetchData=async()=>{
62
+
try{
63
+
constresponse=awaitpromise;
64
+
console.log(response);
65
+
data.rating=5;
66
+
data.tip=0.2;
67
+
data.pay=10;
68
+
data.review=5;
69
+
returndata;// return the data after setting it in the object.
70
+
}catch(err){
71
+
console.log(err);
72
+
data.rating=1;
73
+
data.tip=0;
74
+
data.pay=0;
75
+
data.review=1;
76
+
returndata;// return the data after setting it in the object.
77
+
}
78
+
};
79
+
80
+
// Here, fetchData() function is a promise and you can only retrieve data from a promise using two methods : 1. .then() and 2.Async/await() function .
81
+
// You cannot console.log fetchData() directly thinking it as a normal function and cannot use await because to use await , you have to first have a async function outside.
82
+
83
+
// fetchData().then((value) => console.log(value)); // calling the function to fetch data.
84
+
85
+
constdisplay=async()=>{
86
+
constdata=awaitfetchData();
87
+
console.log(data);
88
+
};
89
+
90
+
display();// calling the function to fetch data and display it.
0 commit comments