YogeshChauhan . com

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

PostgreSQL transactions using the BEGIN, COMMIT, and ROLLBACK statements.PostgresAggregate Functions Examples in Postgres for BeginnersPostgresLearn to create your skill bar using CSSCSSJavaScript String fromCharCode() MethodJavaScriptHow to get user’s Browser and Operating Systems information using PHP?PHPObservation of Human Behavior [Shopping Observation Example]Misc