JavaScript - Async - Generation 3 - Async / Await logic

From
https://www.joshwcomeau.com/javascript/promises/

After problems with Promises were established, a version 3 technology was released and called Async / Await.

Sample code

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
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - Async - Generation 2 - Promises</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="used by atom.xls">
</head>
<body>
<h1>JavaScript - Async - Level 2 - Promises</h1>

<script>
// Run JavaScript after the DOM is fully loaded
document.addEventListener('DOMContentLoaded', async function () {
console.log('DOM fully loaded and parsed.');
// Your script logic here

console.log('Start');

await countdown()

// end of event listener
});


async function countdown() {
console.log("5…");
await wait(1000);
console.log("4…");
await wait(1000);
console.log("3…");
await wait(1000);
console.log("2…");
await wait(1000);
console.log("1…");
await wait(1000);
console.log("Happy New Year!");
}

function wait(duration) {
return new Promise((resolve) => {
setTimeout(
() => resolve(),
duration
);
});
}




</script>

</body>

</html>

The trick about Async/Await is that they can only be called from within Async functions. So out handler was modified

document.addEventListener('DOMContentLoaded', async function () {

    console.log('DOM fully loaded and parsed.');

});