-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20-Async-Awiat.html
55 lines (43 loc) · 1.5 KB
/
20-Async-Awiat.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
<!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>Async and Await in javaScript</title>
</head>
<body>
<script>
// Async in js
// there is a special syntax in js to work with promises
// we can make any function to async function and we can await a promise in it
// await method will be use inside a async function
// await method wiil be used with you wnat to fatch data from the server.
//example: 1:
async function sayHello() {
return "hello world";
}
sayHello().then((value) => {
console.log("promise completed sucessfully: " + value);
});
// second method with arrow function
let sayBy = async () => "BY world";
sayBy().then((value) =>
console.log("promise completed sucessfully: " + value)
);
//example: 2: async function with await method
let studentsData = async () => {
// let response= await fetch('https://jsonplaceholder.typicode.com/todos/5')
// let students= await response.json();
// return students
// refactor code:
return (
await fetch("https://jsonplaceholder.typicode.com/todos/5")
).json();
};
studentsData()
.then((value) => console.log(value))
.catch((error) => console.log(error));
</script>
</body>
</html>