Understanding Async/Await in JavaScript
Tags: javascript, await, programming, webdev
Published: 2022-08-30 15:28:19

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 function
async function asyncRegularFunction() {
  let data = await ASYNCHRONOUS_OPERATION();
  console.log(data);
}
asyncRegularFunction();


// Using arow function
const 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le42tp4d4vsceu48v40b.png)


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 ([jsonplaceholder]("https://jsonplaceholder.typicode.com")) 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.

My name is Daniel Dasaolu and I am a Frontend Vue JS developer. I am passionate about JavaScript concept especially in those areas that proves extra difficult for developers. If this article have been helpful, please let me know in the comment section. You are also welcome to post challenges you are facing and I will be happy to help you address them in simpler terms.

You can connect to me on Twitter [@archyscript](https://twitter.com/ArchyScript) and  [Daniel Dasaolu](https://www.linkedin.com/in/archyscript/) on LinkedIn


Happy coding 💻💻!
Stay creative ✌✌