|
| 1 | +// callbacks, promises, async/await |
| 2 | +// must have async |
| 3 | +// await waits till promises is settled |
| 4 | +// error handling - try / catch |
| 5 | + |
| 6 | +/* |
| 7 | +just for reference: |
| 8 | +#await is promise resolved |
| 9 | +async function someFunction(){ |
| 10 | + await |
| 11 | +} |
| 12 | +
|
| 13 | +const otherFunctions = async() => { |
| 14 | + await |
| 15 | +} |
| 16 | +
|
| 17 | +*/ |
| 18 | +const heading1 = document.querySelector('.one'); |
| 19 | +const heading2 = document.querySelector('.two'); |
| 20 | +const heading3 = document.querySelector('.three'); |
| 21 | +const btn = document.querySelector('.btn'); |
| 22 | + |
| 23 | +btn.addEventListener('click', async () => { |
| 24 | + // log data get hello |
| 25 | + // displayColors().then((data) => console.log(data)); |
| 26 | + |
| 27 | + // and here no need then and change use await |
| 28 | + const result = await displayColors(); |
| 29 | +}); |
| 30 | + |
| 31 | +async function displayColors() { |
| 32 | + // here await make sure promise is settled |
| 33 | + try { |
| 34 | + await changeColors(1000, heading1, 'red'); |
| 35 | + await changeColors(1000, heading2, 'green'); |
| 36 | + await changeColors(1000, heading3, 'blue'); |
| 37 | + } catch (error) { |
| 38 | + console.log(error); |
| 39 | + } |
| 40 | + // return `hello`; |
| 41 | +} |
| 42 | + |
| 43 | +// membuat promises function |
| 44 | +// callbackfunction is time, element, colors |
| 45 | +function changeColors(time, element, colors) { |
| 46 | + return new Promise((resolve, reject) => { |
| 47 | + // if exist |
| 48 | + if (element) { |
| 49 | + setTimeout(() => { |
| 50 | + element.style.color = colors; |
| 51 | + resolve(); |
| 52 | + }, time); |
| 53 | + } else { |
| 54 | + reject(new Error(`Your element is failed cause ${element}`)); |
| 55 | + } |
| 56 | + }); |
| 57 | +} |
0 commit comments