Reputation:
i can't understand why use Asynchronous and await when fetch data from server
Upvotes: 2
Views: 1339
Reputation: 657058
A network request from a client to a server, possibly over a long distance and slow internet can take an eternity in CPU time scales. If it weren't async, the UI would block until the request is completed.
With async execution the UI thread is free to update a progress bar or render other stuff while the framework or Operating System stack is busy on another thread to send and receive the request your code made.
Most other calls that reach out to the Operating System for files or other resources are async for the same reason, while not all of them are as slow as requests to a remote server, but often you can't know in advance if it will be fast enough to not hurt your frame rate and cause visible disruption or janks in the UI.
await
is used to make code after that statement starting with wait
is executed only when the async request is completed. async
/ await
is used to make async code look more like sync code to make it easier to write and reason about.
Upvotes: 4
Reputation: 53
Async helps a lot with scalability and responsiveness.
Using synchronous request blocks the client until a response has been received. As you increase concurrent users you basically have a thread per user. This can create a lot of idle time, and wasted computation. One request gets one response in the order received.
Using asynchronous requests allows the client to receive requests/send responses in any random order of execution, as they are able to be received/sent. This lets your threads work smarter.
Here's a pretty simple and solid resource from Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Asynchronous_request
Upvotes: 2