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();
1function resolveAfter2Seconds() {
2 return new Promise(resolve => {
3 setTimeout(() => {
4 resolve('resolved');
5 }, 2000);
6 });
7}
8
9//async function:
10async function asyncCall() {
11 console.log('calling');
12 const result = await resolveAfter2Seconds();
13 console.log(result);
14 // expected output: 'resolved'
15}
16
17asyncCall();
1function hello() {
2 return new Promise((resolve,reject) => {
3 setTimeout(() => {
4 resolve('I am adam.');
5 }, 2000);
6 });
7}
8async function async_msg() {
9 try {
10 let msg = await hello();
11 console.log(msg);
12 }
13 catch(e) {
14 console.log('Error!', e);
15 }
16}
17async_msg(); //output - I am adam.