Q:

async and await

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
async function showAvatar() {

  // read our JSON
  let response = await fetch('/article/promise-chaining/user.json');
  let user = await response.json();

  // read github user
  let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
  let githubUser = await githubResponse.json();

  // show the avatar
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

  // wait 3 seconds
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser;
}

showAvatar();
3
async function showAvatar() {
	// read
  	await setTimeout(resolve, 3000);
    // read next 3s
}

showAvatar();
0
async function f() {

  try {
    let response = await fetch('/no-user-here');
    let user = await response.json();
  } catch(err) {
    // catches errors both in fetch and response.json
    alert(err);
  }
}

f();
0
function afterPrintSave() {
    Xrm.Page.data.save().then(
        function () {
            resolve();
        },
        function (err) {
            resolve(alert(err.message));
        }
    );
}
0
function delayResult() {
 return new Promise(resolve => {
   setTimeout(() => {
     resolve(‘Done’);
   }, 5000)
 })
}
async function getResult() {
 let result = await delayResult();
 return result;
}
getResult();
0
await async
-1

New to Communities?

Join the community