1(async () => {
2 let response = await fetch('/article/promise-chaining/user.json');
3 let user = await response.json();
4 ...
5})();
1// Old School Javascript Invoke
2(async function() {
3 await someAsyncFunction();
4})();
5
6//New ES6 Javascript Invoke
7(async () => {
8 await someAsyncFunction();
9})();
1const data = async () => {
2 const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
3
4 console.log(await got.json())
5}
6
7data();
1async function showAvatar() {
2
3 // read our JSON
4 let response = await fetch('/article/promise-chaining/user.json');
5 let user = await response.json();
6
7 // read github user
8 let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
9 let githubUser = await githubResponse.json();
10
11 // show the avatar
12 let img = document.createElement('img');
13 img.src = githubUser.avatar_url;
14 img.className = "promise-avatar-example";
15 document.body.append(img);
16
17 // wait 3 seconds
18 await new Promise((resolve, reject) => setTimeout(resolve, 3000));
19
20 img.remove();
21
22 return githubUser;
23}
24
25showAvatar();
1/* Notes:
2 1. written like synchronous code
3 2. compatible with try/catch blocks
4 3. avoids chaining .then statements
5 4. async functions always return a promise
6 5. function pauses on each await expression
7 6. A non promise value is converted to
8 Promise.resolve(value) and then resolved
9*/
10
11// Syntax
12// Function Declaration
13async function myFunction(){
14 await ... // some code goes here
15}
16
17// Arrow Declaration
18const myFunction2 = async () => {
19 await ... // some code goes here
20}
21
22 // OBJECT METHODS
23
24const obj = {
25 async getName() {
26 return fetch('https://www.example.com');
27 }
28}
29
30// IN A CLASS
31
32class Obj {
33 // getters and setter CANNOT be async
34 async getResource {
35 return fetch('https://www.example.com');
36 }
37}
38
1console.log("I");
2
3// This will be shown after 2 seconds
4
5setTimeout(()=>{
6 console.log("eat");
7},2000)
8
9console.log("Ice Cream")
10