dots Created with Sketch.
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.

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
user_can vs current_user_can in WordPressWordPressHow does AdSense calculate page loading time?JavaScriptHow to create a link tag button using CSS?CSSSelector Lists and Combinators in SCSS (Sass)SCSSWhat’s new in Constructor in PHP 8?PHPLearn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHP