0
Q:

await in node js

const data = async ()  => {
  const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  console.log(await got.json())
}

data();
5
/* Notes:
	1. written like synchronous code
    2. compatible with try/catch blocks
    3. avoids chaining .then statements
    4. async functions always return a promise
    5. function pauses on each await expression
    6. A non promise value is converted to 
       Promise.resolve(value) and then resolved
*/

// Syntax
// Function Declaration
async function myFunction(){
  await ... // some code goes here
}
  
// Arrow Declaration
const myFunction2 = async () => {
  await ... // some code goes here
}
  
 // OBJECT METHODS

const obj = {
	async getName() {
		return fetch('https://www.example.com');
	}
}

// IN A CLASS

class Obj {
	// getters and setter CANNOT be async
	async getResource {
		return fetch('https://www.example.com');
	}
}
  
11
// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

async function layer(x)
{
  const value = await square(x);
  console.log(value);
}

layer(10);
0
// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

square(10).then(data => {
  console.log(data);
});
0
// Normal Function
function add(a,b){
  return a + b;
}
// Async Function
async function add(a,b){
  return a + b;
}
0
await async
-1

New to Communities?

Join the community