JS Async Await - MacKittipat/note-developer GitHub Wiki

Reference

Sample code

function getmessage() {
  console.log(new Date().toUTCString() + '>>> 4');
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(new Date().toUTCString() + '>>> 5');
      resolve('Hello');
    }, 3000);
  });
}

// Using async simply implies that a promise will be returned, 
// and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.
async function printMessage() {
  console.log(new Date().toUTCString() + '>>> 3');
  // await can be use inside async function only. 
  // The code will pause here until promise is returned.
  let result = await getmessage();
  console.log(new Date().toUTCString() + '>>> ' + result);
}


console.log(new Date().toUTCString() + ' >>> 1');
printMessage();
console.log(new Date().toUTCString() + '>>> 2'); // This line will not be blocked.

Output :

Sun, 19 Apr 2020 03:29:00 GMT >>> 1
Sun, 19 Apr 2020 03:29:00 GMT>>> 3
Sun, 19 Apr 2020 03:29:00 GMT>>> 4
Sun, 19 Apr 2020 03:29:00 GMT>>> 2
Sun, 19 Apr 2020 03:29:03 GMT>>> 5
Sun, 19 Apr 2020 03:29:03 GMT>>> Hello