Skip to content

Commit 41fc83f

Browse files
committed
Async/Await
1 parent 314d96f commit 41fc83f

File tree

2 files changed

+63
-9
lines changed

2 files changed

+63
-9
lines changed

app.js

+34-9
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,44 @@
11
// callbacks, promises, async/await
2-
// what if
3-
// no resolve - then will no execute
4-
// one is rejected - dependent functionality will get ignored
2+
// must have async to use await
3+
// await waits till promise is settled i.e either resolved or rejected
4+
// error handling - try/catch
5+
// async function by itself always returns a promise so we can use .then on it
56

67
const heading1 = document.querySelector(".heading-1");
78
const heading2 = document.querySelector(".heading-2");
89
const heading3 = document.querySelector(".heading-3");
910
const btn = document.querySelector(".btn");
1011

11-
btn.addEventListener("click", () =>
12-
addColor(1000, heading1, "red")
13-
.then(() => addColor(2000, heading2, "green"))
14-
.then(() => addColor(1000, heading3, "blue"))
15-
.catch((error) => console.log(error))
16-
);
12+
/* Async/Await Syntax */
13+
// async function someFunction() {
14+
// await
15+
// }
16+
17+
// const otherFunction = async () => {
18+
// await
19+
// };
20+
21+
btn.addEventListener("click", async () => {
22+
// displayColor().then((data) => {
23+
// console.log(data);
24+
// });
25+
26+
const result = await displayColor();
27+
console.log(result);
28+
});
29+
30+
/* This returns a promise */
31+
async function displayColor() {
32+
try {
33+
const first = await addColor(1000, heading1, "red");
34+
await addColor(2000, heading2, "green");
35+
await addColor(1000, heading3, "blue");
36+
console.log(first);
37+
} catch (error) {
38+
console.log(error);
39+
}
40+
return "hello";
41+
}
1742

1843
function addColor(time, element, color) {
1944
return new Promise((resolve, reject) => {

promise-dom-example.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// callbacks, promises, async/await
2+
// what if
3+
// no resolve - then will no execute
4+
// one is rejected - dependent functionality will get ignored
5+
6+
const heading1 = document.querySelector(".heading-1");
7+
const heading2 = document.querySelector(".heading-2");
8+
const heading3 = document.querySelector(".heading-3");
9+
const btn = document.querySelector(".btn");
10+
11+
btn.addEventListener("click", () =>
12+
addColor(1000, heading1, "red")
13+
.then(() => addColor(2000, heading2, "green"))
14+
.then(() => addColor(1000, heading3, "blue"))
15+
.catch((error) => console.log(error))
16+
);
17+
18+
function addColor(time, element, color) {
19+
return new Promise((resolve, reject) => {
20+
if (element) {
21+
setTimeout(() => {
22+
element.style.color = color;
23+
resolve();
24+
}, time);
25+
} else {
26+
reject(new Error(`There is no such element ${element}`));
27+
}
28+
});
29+
}

0 commit comments

Comments
 (0)