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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Reading Multiple Inputs in SwiftSwiftHow to check if the page is the home page in WordPress?WordPressHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPHow states work in React?ReactPHP Login System using PDO Part 2: Login using Email or UsernamePHPCSS Overflow Property with ExamplesCSS