|
1 | 1 | // 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 |
5 | 6 |
|
6 | 7 | const heading1 = document.querySelector(".heading-1");
|
7 | 8 | const heading2 = document.querySelector(".heading-2");
|
8 | 9 | const heading3 = document.querySelector(".heading-3");
|
9 | 10 | const btn = document.querySelector(".btn");
|
10 | 11 |
|
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 | +} |
17 | 42 |
|
18 | 43 | function addColor(time, element, color) {
|
19 | 44 | return new Promise((resolve, reject) => {
|
|
0 commit comments