Synchronous HTTP calls in Angular using Async and Await
Tags: angular, javascript, typescript
Published: 2021-08-16 20:14:07

Observables in Angular offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values. But some times we may want to wait for the response from previous HTTP call or load default settings for an application. In that case, we use Async and Await functions to achieve this. This blog post explains the steps and provides code samples. As usual complete code uploaded to [**Github**](https://github.com/pavankjadda/Angular-Async-Await)

Async & Await
=============

An asynchronous function is a function that operates asynchronously via the event loop, using an implicit [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to return its result. But the syntax and structure of your code using async functions are much more like using standard synchronous functions. The `await` operator is used to wait for a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). It can only be used inside an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).

```
async method()   
{  
  var x = await resolveAfter2Seconds(10);  
  console.log(x); // 10  
}
```

Technologies
============

1.  Angular 9+
2.  [**json-server**](https://github.com/typicode/json-server) (to mock Rest API)

Synchronous HTTP call in Angular 9+
===================================

> _If you have Java, C# etc. backend available, skip the steps 1,2, 3 and go to step 4 directly_

`[**json-server**](https://github.com/typicode/json-server)` helps to mock the backend REST API and stores entered data. In this application, we demonstrate a simple use case with two operations, create new employee and fetch a list of employees.

1.  First, create `db.json` file, that holds employee information

```
{  
 "employees":   
\[  
  {  
   "id": 1,  
   "firstName": "John",  
   "lastName": "Reese"  
  },  
  {  
   "id": 2,  
   "firstName": "Steve",  
   "lastName": "Rogers"  
  }  
 \]  
}
```

2\. Add `json-server` dependency and `json-server —- watch db.json`  the script in **package.json** as shown below

```
"dependencies":   
{     
  ....,      
  "json-server": "^0.14.2",  
  ....,},  
"scripts":   
{  
  ....,  
  "json-server": "json-server --watch db.json"  
  ....,  
}
```

3\. start json-server by executing following command on the project root folder

```
$ json-server —-watch db.json
```

4\. Now that, backend mock REST API server is available, let’s build the front end. In order for async to work, both the component method and service method should annotate with **async** and **await**.

app.component.ts
================

app.component.ts

**employee.service.ts**
=======================

employee.service.ts

**5\.** `createEmployee()` method on component class annotated with `**async**` and `employeeService.createEmployee()` annotated with `**await**`. This instructs the compiler to wait for the execution of `this.employeeService.createEmployee()` method, then execute `this.getEmployees()`

**5\.** `createEmployee()` method on component class annotated with `**async**` and `employeeService.createEmployee()` annotated with `**await**`. This instructs the compiler to wait for the execution of `this.employeeService.createEmployee()` method, then execute `this.getEmployees()`

6\. When you click on **CreateNew** button on the HTML page, it creates a new employee with Random Id, then `this.getEmployees()`  gets a list of employees

The code uploaded [**Github**](https://github.com/pavankjadda/Angular-Async-Await) for reference. Download the repository and execute it.