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();
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
1async function f() {
2
3 try {
4 let response = await fetch('/no-user-here');
5 let user = await response.json();
6 } catch(err) {
7 // catches errors both in fetch and response.json
8 alert(err);
9 }
10}
11
12f();
1function resolveAfter2Seconds() {
2 return new Promise(resolve => {
3 setTimeout(() => {
4 resolve('resolved');
5 }, 2000);
6 });
7}
8
9async function asyncCall() {
10 console.log('calling');
11 const result = await resolveAfter2Seconds();
12 console.log(result);
13 // expected output: 'resolved'
14}
15
16asyncCall();
17