Hello Friends , welcome to my article . In this article we will look “what async await in js is ? ” and we will also see some examples of async await in js .

Async Await in js

“Async Await” is simply a syntax in js to work with promises in more comfortable fashion . It is very easy to understand and use .

Start with Async functions

“async” is a keyword in javascript which can be used before a function declaration to declare that function as an async function . It looks like this

async function j() {
  return "hello";
}

The motive of “async” keyword before a function is it tells the user that the function will return a resolved promise automatically .

Let’s try to test how this “async” keyword is working

async function j() {
  return "hello";
}

j().then(alert); // hello

Now if you don’t want to use “async” keyword before a function and wants to return a promise , then you can explicitly use “Promise” object .

function j() {
  return Promise.resolve("hello");
}

j().then(alert);

So that’s all about “async” , it makes a function return promise when applied before a function’s name .

Await Keyword

The keyword “await” works only inside an async function , it makes javascript wait until promise resolves and returns it’s result .

Let’s talk about the syntax of “await” keyword

let hello = await promise; 

“await” keyword is always used inside an async function . Here’s an example

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("hello world"), 2000)
  });

  let result = await promise; // wait for the promise to resolve

  alert(result); // "hello world"
}

f();

Here is another example

function greeting() {

  return new Promise(resolve => {
    setTimeout(function() {
      resolve("hi") ;
    }, 2000)
  })

}

async function getGreeting(){

   var hello = await greeting(); //get greeting after 2 seconds
   console.log(hello);

}

What if we use await in non-async function ?

if we try to use “await” keyword in non-async function then we will get a syntax error

function greeting(){

   let result = await fetch('/api/fetch/article.json') ; // syntax error
   result
   .then(response => response.json())
   .then(data => console.log(data));

}

As instructed earlier “await” can only be used inside an “async” defined functions .

I will post more about “async await” in up coming articles . Stay tuned and be happy 🙂

Follow me on Linkedin : Anand Raj

Join Our Telegram community of developers over here

Want to learn Firebase Chat application Development with Javascript and Jquery ? click here

Next Article : Make your own javascript library from scratch