javascript async function return value code example

Example 1: how to make an async function

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();

Example 2: async await javascript

function hello() {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('I am adam.');
    }, 2000);
  });
}
async function async_msg() {
  try {
    let msg = await hello();
    console.log(msg);
  }
  catch(e) {
    console.log('Error!', e);
  }
}
async_msg(); //output - I am adam.

Example 3: async await

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

showAvatar();

Example 4: async function someFunction()

async function someFunction() {
	console.log("someFunction");
 }
 
 Console.log("Start");
 someFunction();
 console.log("End");