Isotopia
0
Q:

async

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

//async function:
async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();
7
/* 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 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 resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();
0
//you can only return a value from an async function by passing in a callback function like so: 
function longRunningFunction(param1, callback){
    setTimeout(function(){
         var results="O High there!";
         callback(results);
    }, 2000);
} 

//then call the async function and pass the callback function like so
longRunningFunction("morning", function(result){
  alert(result);
});
-1

New to Communities?

Join the community