Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 30, 2022 03:28 pm GMT

Understanding Async/Await in JavaScript

The word async before a function means one simple thing: a function always returns a promise.
The keyword await makes JavaScript wait until that promise settles and returns its result.

The async/await syntax in JavaScript ES7 makes it easier to coordinate asynchronous promises.

An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete (resolved or rejected).

Async/await construct allows us to express logic more precise with excellent readable and maintainable code.

Basic Format

// Using regular functionasync function asyncRegularFunction() {  let data = await ASYNCHRONOUS_OPERATION();  console.log(data);}asyncRegularFunction();// Using arow functionconst asyncArrowFunction = async () => {  let data = await ASYNCHRONOUS_OPERATION();  console.log(data);}asyncArrowFunction();In each functions above, the data variable awaits response from ASYNCHRONOUS_OPERATION method

What is a promise?

A Promise is a special JavaScript object, it produces a value after an asynchronous (async) operation completes successfully, or an error if it does not complete successfully due to time out, network error, and so on.

  • Promise constructor takes only one argument which is a callback function (and that callback function is also known as anonymous function).
  • Callback function takes two arguments, resolve and reject
  • Perform operations inside the callback function and if everything went well then call resolve.
  • If desired operations do not go well then call reject.
var myPromise = new Promise((resolve, reject) => {  const var1 = "alien";  const var2 = "alien"  if(var1 === var2) {    resolve();  } else {    reject();  }});myPromise  .then(function () {      console.log('You are an Alien');  })  .catch(function () {      console.log('Sorry, an error occurred');  });// expected output: Success, You are an Alien

The flowchart below further explains the concept of async/await syntax

Image description

To understand how async/await promises work in JavaScript, I will illustrate it with the simple process of delivering an item to a client from the diagram above.

To make this process asynchronous, every steps must be followed in this order:

  • store keeper gets an order,
  • check if order is available,
  • accepts order,
  • package item(s),
  • delivers item(s) to the client and receives payment (in an instance of payment on delivery).

In this case, it is important that our store keeper follows the above process in that exact order because every process are dependent on the response received from the previous.
This prevents potential errors during delivery and ensures that clients receive what they have ordered in the correct qualities and quantities, with all procedures being followed correctly.

A more practical example

A simple function to resolve a Promise after (5) seconds.

function resolveAfterFiveSeconds() {  return new Promise(resolve => {    setTimeout(() => {      resolve('resolved');    }, 5000);  });}async function asyncCall() {  console.log('calling');  const result = await resolveAfterFiveSeconds();  console.log(result); }asyncCall(); // expected output // "calling" immediately // "resolved" after five seconds

Also, the code below is a sample of how to fetch todos data from an API (jasonplaceholder) using asynchronous function, await the response and then save it in a todos variable

const API_URL = "https://jsonplaceholder.typicode.com/todos"let response = await fetch(API_URL);let todos = await response.json();console.log(todos);// expected output: an array of todos from **json placeholer**

Yeah !!! You get the idea.
This is just an introduction to the async/await format of handling promise in JavaScript. If you're new to async functions I hope this shed some light on how they work and what they do. That'll be it for today.

In conclusion, async/await helps fetch data asynchronously from multiple databases or APIs in a certain order and is a special syntax to work with promises in a more comfortable fashion.

Happy coding !
Stay creative


Original Link: https://dev.to/archyscript/understanding-asyncawait-in-javascript-561d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To