1const data = async () => {
2 const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
3
4 console.log(await got.json())
5}
6
7data();
1// server.js
2
3function square(x) {
4 return new Promise(resolve => {
5 setTimeout(() => {
6 resolve(Math.pow(x, 2));
7 }, 2000);
8 });
9}
10
11async function layer(x)
12{
13 const value = await square(x);
14 console.log(value);
15}
16
17layer(10);
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
1// Normal Function
2function add(a,b){
3 return a + b;
4}
5// Async Function
6async function add(a,b){
7 return a + b;
8}
1// server.js
2
3function square(x) {
4 return new Promise(resolve => {
5 setTimeout(() => {
6 resolve(Math.pow(x, 2));
7 }, 2000);
8 });
9}
10
11square(10).then(data => {
12 console.log(data);
13});