-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathindex-solution.js
More file actions
151 lines (127 loc) · 4.57 KB
/
Copy pathindex-solution.js
File metadata and controls
151 lines (127 loc) · 4.57 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
// Week 3 demo – Promises & async/await (solution)
// JSONPlaceholder only (reliable in the browser). Session plan may mention Open Notify —
// same async ideas, different URL.
const USER_URL = "https://jsonplaceholder.typicode.com/users/1";
const POST_URL = "https://jsonplaceholder.typicode.com/posts/1";
const TODO_URL = "https://jsonplaceholder.typicode.com/todos/1";
function showOutput(text) {
const el = document.getElementById("out");
if (el) {
el.textContent = text;
}
}
// =============================================================================
// Async/await – simple usage
// =============================================================================
// Task: Load USER_URL with async/await
async function getUser() {
const response = await fetch(USER_URL);
const user = await response.json();
showOutput(JSON.stringify(user, null, 2));
}
// Next: Exercise 1
// =============================================================================
// Why use Promises? :: Callback Hell
// =============================================================================
// Show Callback Hell example in https://www.npmjs.com/package/q
// =============================================================================
// Promise consumption
// =============================================================================
// Task: Load one of the resources (e.g. USER_URL); show success or error on the page using .then / .catch only.
function loadOneResourceWithThen() {
showOutput("Loading…");
fetch(USER_URL)
.then((response) => response.json())
.then((data) => {
showOutput(JSON.stringify(data, null, 2));
})
.catch((error) => {
showOutput(String(error));
});
}
// Next: Chaining examples
// Next: Exercise 2
// =============================================================================
// Promise creation
// =============================================================================
// Task: Create a Promise that resolves after 1 second and shows "It worked" on the page.
// Task: Create demoOrderPizza: a pizza-order Promise — after a 'baking' delay it either resolves with a pizza you can eat (show that on the page) or rejects if baking failed (show the failure on the page).
function oneSecondMessage() {
showOutput("…");
const oneSecondTimeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 1000);
});
oneSecondTimeoutPromise.then(() => {
showOutput("It worked");
});
}
function demoOrderPizza() {
showOutput("Baking… (3s for demo)");
const pizzaMakingTime = 3000;
const didPizzaBakingSucceed = true;
const pizza = "Macaroni pizza";
const orderPizzaPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (didPizzaBakingSucceed) {
resolve(pizza);
} else {
reject("The pizza was a mess");
}
}, pizzaMakingTime);
});
orderPizzaPromise
.then((p) => {
showOutput(`Let's eat the ${p}`);
})
.catch((error) => {
showOutput(`Let's eat nothing: ${error}`);
});
}
// Next: Exercise 3
// Next: Exercise 4
// =============================================================================
// Back to async/await (try / catch)
// =============================================================================
// Task: improve getUser to use try/catch to handle errors and show the error on the page.
async function getUserWithTryCatch() {
try {
const response = await fetch(USER_URL);
const user = await response.json();
showOutput(JSON.stringify(user, null, 2));
} catch (err) {
showOutput(String(err));
}
}
// Next: Exercise 5
// =============================================================================
// Promise.all
// =============================================================================
async function demoPromiseAll() {
showOutput("Loading both…");
try {
const [userRes, postRes] = await Promise.all([
fetch(USER_URL),
fetch(POST_URL),
]);
const [user, post] = await Promise.all([userRes.json(), postRes.json()]);
const summary = [
"User: " + user.name + " (" + user.email + ")",
"Post: " + post.title,
].join("\n");
showOutput(summary);
} catch (e) {
showOutput(String(e));
}
}
// Next: Exercise 6
// =============================================================================
// (Optional) Infinite loop via Promises
// =============================================================================
function promiseLoop() {
return Promise.resolve().then(() => {
console.log("tick");
return promiseLoop();
});
}