1const data = async () => {
2 const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
3
4 console.log(await got.json())
5}
6
7data();
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.
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
1If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
1The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
2