Async await basic tutorials and examples

This tutorial explains async and awaits tutorials and examples.

Async functions are used to achieve asynchronous programming.

async functions always return a promise. If the function is not returning the promise, It wraps the result in a promise

How to declare async functions in multiple ways

Async functions are used to do asynchronous functions. It pauses the current execution and runs the execution in a separate queue called the event queue. In Real-time, Async function does call API processing

  • async normal functions function are declared with the keyword async. It is a normal function
async function getMessage() {
return "Welcome";
}

which is equal to

async function getMessage() {
  return Promise.resolve("Welcome");
}
  • async function anonymous expressions Async functions are also declared anonymous and have no name. These can be assigned a variable
const variable = async function () {
  // do something
};

calling Async function returns always Promise. You can explicitly return a promise or value that wrapped with a value

console.log(getMessage())
  • Async Arrow functions examples

Arrow functions declared assigned to javascript variables. It is declared with either arguments or without arguments Async Arrow function without arguments

const getMessage = async () => {
console.log("Hello ")
}

Async with single arguments. Single arguments parenthesis are optional

const getMessage = async (msg) => {
console.log("Hello ",msg)
}
or
const getMessage = async msg => {
console.log("Hello ",msg)
}

Multiple arguments to arrow async functions

const getMessage = async (msg1,msg2) => {
console.log("Hello ",msg)
}
  • Async function also declared with static
static myfunc = async () => {
console.log("static function ")
}

How to Call async functions

Async functions are asynchronous that always return Promise.

Calling the async function always returns Promise.

  • using await keyword async functions are called with the await keyword.

await is waiting for a function to finish its execution. await only called in an async function.

async function getMessage() {
return "Welcome";
}
console.log(getMessage())
async function callMessage() {
const result = await getMessage();
console.log(result); // will print "welcome"
}

callMessage()

If you called await in without async functions, It throws below error

async function getMessage() {
  return "Welcome";
}
console.log(getMessage())
 function callMessage() {
  const result = await getMessage();
  console.log(result); // will print "Hello world!"
}

callMessage()

SyntaxError: await is only valid in async functions and the top-level bodies of modules

  • How to call async functions in synchronized functions

You have to use then catch block in synchronized funcitons

then() is used catch successfully resolved promises

async function getMessage() {
return "Welcome";
}
async function callMessage() {
getMessage()
.then(data=>console.log("success",data))
.catch(error=>console.log("error: ",error))
}

callMessage()// Prints success Welcome
  • async functions throws an error

For some reason, async functions throws an error, catch block is called with an error catching

async function getMessage() {
throw "failed";
}
async function callMessage() {
getMessage()
.then(data=>console.log(data))
.catch(error=>console.log("error",error))
}

callMessage() // error failed
  • async functions reject promise, not returning it

In this example, async functions is completed with Promise reject.

Promise is rejecting, but not returning it

async function getMessage() {
  Promise.reject("fail");
}
async function callMessage() {
  getMessage()
    .then((data) => console.log("success", data))
    .catch((error) => console.log("error", error));
}

callMessage();

Above code throws

**[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise was rejected with the reason "fail".] {
  code: 'ERR_UNHANDLED_REJECTION'**
success undefined

node:internal/process/promises:279
triggerUncaughtException(err, true /_ fromPromise _);
^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise was rejected with the reason "fail".] {
code: 'ERR_UNHANDLED_REJECTION'
}

It calls a catch block with an undefined result.

  • async functions returns rejected promise

catch function call back is called with an error

async function getMessage() {
return Promise.reject("fail")
}
async function callMessage() {
getMessage()
.then(data=>console.log("success",data))
.catch(error=>console.log("error",error))
}

callMessage();

Output:

error fail