So, imagine that you have a task: to implement the "Edit Profile" button, by clicking on which a form should appear. And the values ββfor the fields of this form are loaded asynchronously from the server.
Incompatible interface
An example of the implementation of such a button.
What happens here and why this option is bad
As you may have noticed, the response to a click on a button occurs with a long delay. Why is that? Let's look at the chart:
As you can see, in this approach, the script first loads the data and performs the preparatory work, and only then changes the interface. This is mistake.
The interface must somehow respond to user actions as early as possible.
Responsive Interface
Let's make things a little better. In the following example, we create a form and display it immediately . And only then we attach processors and load data from the server.
Let's look at our chart:
As you can see, the total runtime has not changed. However, now the user sees the reaction to their actions much earlier.
Deferred Promise
Did you know that you donβt have to wait for Promise in the same place where you created it?
const promise = fetch() // , , fetch() const response = await promise // promise
So you can minimize downtime - when the browser just waits for the completion of the asynchronous operation and is not busy with anything.
Run long, asynchronous operations as early as possible, but expect them to complete as soon as possible.
Now, bearing in mind this rule, let's get back to our form.
In the following example, we will send a request to download data immediately after a click, but we will not wait for it to complete. Instead of downtime while waiting for a response from the server, we will do a useful job - create a form and display it.
And here is what we get:
As you can see in the graph, at the very beginning two processes are executed in parallel. Thus, we saved almost a second of runtime.
I hope this material will be useful to someone