Async & Await
In Angular, Observables are a powerful tool for handling asynchronous operations, events, and streams of data. However, there are scenarios where you need to halt execution until a previous HTTP request completes — for example, when loading default application settings or preparing dependencies before proceeding. In these cases, combining async and await with Angular's HTTP client offers a straightforward solution. The following guide walks through the necessary steps with code examples. The full source code is available on GitHub.
An async function runs asynchronously through the event loop, returning its result via an implicit Promise. Despite this asynchronous nature, the code structure resembles regular synchronous functions. The await keyword pauses execution until a Promise resolves, and it is only valid inside an async function.
async method()
{
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
Technologies
- Angular 9+
- json-server (for mocking a REST API)
Synchronous HTTP Call in Angular 9+
If you already have a backend service (Java, C#, etc.) available, you can skip steps 1, 2, and 3 and proceed directly to step 4.
json-server provides a convenient way to simulate a backend REST API while storing any data you submit. This example demonstrates a basic workflow with two operations: creating a new employee and retrieving the employee list.
- Start by creating a
db.jsonfile that will store the employee data.
{
"employees":
\[
{
"id": 1,
"firstName": "John",
"lastName": "Reese"
},
{
"id": 2,
"firstName": "Steve",
"lastName": "Rogers"
}
\]
}
- Add
json-serveras a dependency and include the scriptjson-server --watch db.jsonin your package.json file, as shown below.
"dependencies":
{
....,
"json-server": "^0.14.2",
....,},
"scripts":
{
....,
"json-server": "json-server --watch db.json"
....,
}
- Launch the json-server by running the following command from the project root directory.
$ json-server —-watch db.json
- With the mock REST API running, you can now focus on the frontend. To leverage
async/await, both the component method and the service method must be marked as async and use await at the appropriate points.
app.component.ts
app.component.ts
employee.service.ts
employee.service.ts
- The
createEmployee()method in the component class is declared asasync, and within it, the call toemployeeService.createEmployee()is prefixed withawait. This tells the runtime to pause here until that service method finishes, after whichthis.getEmployees()is invoked.
- When the CreateNew button on the HTML page is clicked, a new employee with a randomly generated ID is created. Once that creation is complete,
this.getEmployees()retrieves and displays the updated list of employees.
The code is available on GitHub for reference. Clone the repository and run it locally to see the behavior in action.
