-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_async.js
127 lines (110 loc) · 2.58 KB
/
test_async.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
print = console.log;
print("1");
print("2");
setTimeout(() => {
print("callback fired");
}, 2000);
print("3");
print("4");
var url = "https://jsonplaceholder.typicode.com";
const getTodos = (resource) => {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.addEventListener("readystatechange", () => {
//console.log(request, request.readyState);
if (request.readyState === 4 && request.status === 200) {
//console.log(request.responseText);
const data = JSON.parse(request.responseText);
resolve(data);
} else if (request.readyState === 4) {
//print('could not fetch the data');
// callback("could not fetch the data", undefined);
reject("error!!");
}
});
// request.open("GET", url + "/todos/2");
request.open("GET", resource);
request.send();
});
};
console.log(1);
console.log(2);
// getTodos("todos.json", (err, data) => {
// print("callback fired");
// if (err) print(err);
// else print(data);
// //print(err, data);
// });
getTodos("todos.json")
.then((data) => {
console.log("promise resolved:", data);
return getTodos(url + "/todos/1");
})
.then((data) => {
console.log("promise 2 resolved:", data);
return getTodos(url + "/todos/2");
})
.then((data) => {
console.log("promise 3 resolved:", data);
})
.catch((err) => {
console.log("promise rejected:", err);
});
console.log(3);
console.log(4);
// promise example
const getSomething = () => {
return new Promise((resolve, reject) => {
resolve("some data");
reject("oops! error");
});
};
// getSomething().then(
// (data) => {
// console.log(data);
// },
// (error) => {
// console.log(error);
// }
// );
getSomething()
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
// fetch api
fetch("todos.json")
.then((response) => {
console.log("resolved:", response);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log("rejected:", err);
});
// async and await
console.log("async started");
const getData = async () => {
const response = await fetch("todoss.json");
if (response.status !== 200) {
throw new Error("error in fetching data");
}
// console.log(response);
const data = await response.json();
return data;
};
console.log(1);
console.log(2);
getData()
.then((data) => {
console.log("resolved:", data);
})
.catch((err) => {
console.log("rejected:", err.message);
});
console.log(3);
console.log(4);