JS: Asynchronous programming
Theory: HTTP Requests
Asynchrony occurs whenever there are input/output operations, including file operations and any network communication. This is especially relevant for HTTP requests, which no web application can do without. Any application’s frontend constantly makes requests to servers and cannot do anything without them.
To understand this concept, you need to understand how the HTTP API works.
Asynchrony is a natural part of network requests. The server takes some time to accept the request, process it, and send back the response. And the response may not come if there are network errors.
At the most basic level, an HTTP request and response are just texts sent to the server and back from the server to the client:
In application code, the actual structure of the request and response is hidden for easier management. The requests themselves are processed by HTTP clients, libraries dedicated to handling requests and responses via HTTP. In the JavaScript world, we can use the axios library for this.
Below you can see a simple example:
The interface of this library is pretty straightforward. For each HTTP method, the corresponding method of the axios object is defined inside the library. The example above uses get(), but you can also use post(), delete(), and others.
Each of these methods takes a URL as its first parameter. Subsequent parameters vary depending on the meaning of the individual methods. The methods themselves are asynchronous, so their usage is usually associated with async/await.
Again, the result of any request is a response object, which represents the response from the server. This object stores both the response and the response data, which has been prepared for convenient processing. For example, to get the response status you just access the response.status property.
To make a POST request, use the post() method. The second parameter of this method takes an object that contains the data that we will send to the server. The Axios is smart enough to present this object as text (as part of the body of the request) and set headers required to process it:
As a rule, HTTP requests don’t execute in packets. In actual code, user actions such as submitting a form or loading data result in a single request. Even though we used asynchrony here, it adds almost no complexity to the code. And thanks to async/await, the code looks like a synchronous one.

