JavaScript async/await Functions

18 Mar 2023  Amiya pattanaik  3 mins read.

What async/await in JavaScript?

Async/await functions, a new addition with ES2017 (ES8), help us even more in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes. The functionality achieved using async functions can be recreated by combining promises with generators, but async functions give us what we need without any extra boilerplate code.

lets take this Example

function playPingPong() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('🏓');
    }, 2000);
  });
}

async function sendMsg() {
  const msg = await playPingPong();
  console.log('Will play:', msg);
}

sendMsg();
Ourtput : Will play: 🏓 <-- after 2 seconds
Here, await is a new operator used to wait for a promise to resolve or reject. It can only be used inside an async function.

Returning Promise

Remember that Async functions always return a promise, so the following may not give the result you’re after:

async function sayHello() {
  return 'Hello DQdigitals!';
}

const b = sayHello();
console.log(b);

// Output: [object Promise] { ... }

Since what’s returned is a promise, you could do something like this instead:

async function sayHello() {
  return 'Hello DQdigitals!';
}

const b = sayHello();
b.then(x => console.log(x));

// Output: Hello DQdigitals!

or you can also just this:

async function sayHello() {
  return 'Hello DQdigitals!';
}
sayHello().then(x => console.log(x));
//Output:  Hello DQdigitals!

Error Handling

Something else that’s very nice about async functions is that error handling is also done completely synchronously, using try…catch statements. Let’s demonstrate by using a promise that will reject half the time:

function generateOneZero() {
  return new Promise((resolve, reject) => {
    const val = Math.round(Math.random() * 1); // 1 or 0, at random
    val ? resolve('yes ..it is one !!') : reject('no ..it is zero !!');
  });
}

// calling function
async function msg() {
  try {
    const msg = await generateOneZero();
    console.log(msg);
  } catch(err) {
    console.log(err);
  }
}

msg(); // yes ..it is one !!
msg(); // no ..it is zero !!
msg(); // no ..it is zero !!
msg(); // yes ..it is one !!
msg(); // yes ..it is one !!
msg(); // no ..it is zero !!
msg(); // no ..it is zero !!
msg(); // no ..it is zero !!
msg(); // no ..it is zero !!
msg(); // yes ..it is one !!

The beauty of async functions is that always return a promise, you can also deal with unhandled errors as you would normally using a catch statement:

async function msg() {
  const msg = await generateOneZero();
  console.log(msg);
}

Conclusion

Before ES2017 (ES8) Async/await functions, JavaScript code that relied on lots of asynchronous events (for example: code that made lots of calls to APIs) would end up in what some called “callback hell” - A chain of functions and callbacks that was very difficult to read and understand. Async and await allow us to write asynchronous JavaScript code that reads much more clearly.

We encourage our readers to treat each other respectfully and constructively. Thank you for taking the time to read this blog post to the end. We look forward to your contributions. Let’s make something great together! What do you think? Please vote and post your comments.

Amiya Pattanaik
Amiya Pattanaik

Amiya is a Product Engineering Director focus on Product Development, Quality Engineering & User Experience. He writes his experiences here.