Yogesh Chauhan's Blog

async function in JavaScript

in JavaScript on April 28, 2021

What’s an async function? A function declared with an async keyword.

async and await keywords goes along together. Basically, you can avoid using promise chains by using these two keywords.

async makes the function behaviour is asynchronous and makes the function return a promise. await, as per the name suggests, make it wait for the promise.

The return value is similar as promise, either resolved with a value or rejected with an error/exception or uncaught within the function.

This is how we write a promise function without async keyword


let promiseEx = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve("Promise request resolved!");
  }, 1000);
});

promiseEx.then(function(value) {
  console.log(value);
});

//"Promise request resolved!"

This is how we can convert it to an async promise


async function asyncPromise() {
  let promiseEx = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve("Promise request resolved!");
    }, 1000);
  });
  console.log(await promiseEx);
}

asyncPromise();
//"Promise request resolved!"

Do you have to have an await expression?

Not really.

You can have none or more than one await expressions.

return value of the await expression = resolved value of the promise

await suspends the function execution till it gets the returned value from promise, either fulfilled value or rejected. That behaviour makes the overall behavior more like synchronous — step by step in a smooth flow. You can also use try / catch blocks with async and await.

await keyword outside of the async function will give you a SyntaxError, it only works inside async function.

Although, you can also use await with JavaScript modules.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to scroll contents of a an element vertically using JavaScript?JavaScriptThe Sort and Compare Functions in JavaScriptJavaScriptWhat is React? Learn the basicsReactSlider animation using CSS transform propertyCSSHow to Install PHP Laravel on MacOS Catalina?PHPHow to create a simple tab interaction using CSS?CSS