React - Asynchronous and Synchronous
Asynchronous and Synchronous
Concept
Motivation
- Communication method where the next task executes only after waiting for the previous task to complete on the server - While enabling simple code implementation, it has the drawback of performance degradation when multiple tasks run concurrently
Asynchronous
- A communication method where subsequent tasks are executed without waiting for a response after sending a request
- Examples include fetching lists of items or performing download operations
- Suitable for processing multiple tasks simultaneously or in parallel
- Can improve overall task performance
- JavaScript frequently uses promises for this purpose
Types of Asynchronous Operations
Ajax
- Asynchronous Javascript And XML, an acronym for a technique that uses JavaScript to asynchronously fetch necessary data from the server and updates only the parts of the page that require modification. - Its primary purpose is to exchange information between the client and server without screen transitions.
Advantages
- Enables asynchronous communication between server and client without page refresh - Improves performance in terms of speed - Requires no separate plugins - Allows interaction with the web application even during HTTP transmission
Axios
- An HTTP-based asynchronous communication library using the Promise API for browsers and Node.js
Features
- Uses the browser's XMLHttpRequest or Node.js's Http API depending on the environment - Uses the Promise API - Automatically converts HTTP requests/responses into JSON format - Allows request cancellation and timeout configuration - Offers more features than Fetch
Comparison with Fetch
Fetch
- As it is a built-in library, it can be used without importing - Some browsers do not support it - Must return a promise and convert it to JSON - Can only pass a response as a rejection if there is a network failure or the request does not complete - For 400/500 errors, you must directly check response.ok
Hope
- Data is transmitted directly - Features such as canceling requests mid-process or setting timeouts are available - When 400/500 errors occur, responses can be caught using reject - Must be imported at the top level of the project
Data Transfer
- response: Passed as an object - fetch: Passed after serialization with JSON.stringify()
Normal Request/Response Check
- response: Verify the status is 200 or check via statusText - fetch: Verify the object contains an ok property
How to Get a Response
- response: Access and obtain the data property of the response object - fetch: Call the json() method on the response object and obtain the JSON object
Promise
-
An object used for asynchronous processing in React, employed for data communication in web services.
-
A Promise has three states
- Pending - The initial state, meaning it has not yet been resolved or rejected - This is the state when an object is created, holding resolve and reject as arguments
- Fulfilled - The state where asynchronous logic processing is complete, and the Promise has returned its result value. 3. Rejected - The state of failure or error in asynchronous logic processing.
-
Starting with ES7, asynchronous code can be written like synchronous code using async/await.
-
Using promises allows you to chain additional promises using then(), increasing the length.
This can be resolved using Async/Await.
-
How to Use
Ajax
- url: The URL to request - type: The HTTP method to execute (GET, POST, PUT, DELETE) - async: Default value is true; set to false for synchronous communication - data: Parameters to transmit - dataType: The data format to return from the server (xml, html, json...)
#### Axios
##### Request
**Basic Structure**
react axios({ url: 'address', method: '', data: { // data to send } })
##### url
- Shipping Address
##### method
- Supports GET, POST, DELETE, PUT, etc.
##### data
- Data to be sent in the body; used when the request method is PUT, POST, or PATCH
##### Response
- When receiving a response, processing is possible using **.then**.
###### Property
- **data**: The response provided by the server - **status**: The HTTP status code from the server - **statusText**: The HTTP status message from the server response - **headers**: The headers returned by the server, with all header names provided in lowercase
- **config**: The configuration set for the request in 'axios' - **request**: The request that generated the response - **browser**: An XMLHttpRequest instance - **Node.js**: A ClientRequest instance
###### Shorthand Methods
- GET, POST, PUT, DELETE 등이 존재한다 - **GET**: axios.get(url[, config]) - **POST**: axios.post(url, data[, config]) - **PUT**: axios.put(url, data[, config]) - **DELETE**: axios.delete(url[, config])
#### Promise
##### Async
- You can convert a regular function into an async function by placing `async` before it. - When used, it does not return a value like a regular function; instead, it returns a fulfilled Promise.
##### Await
- An operator used to await a promise, usable only within async functions
~~~ [rv] = await Expression; ~~~
- **rv**: If it's a Promise, the resolved value is returned; if it's not a Promise, the value itself is returned. - **expression**: A Promise or a value to wait for.
#### Fetch
**Basic Structure**
~~~react fetch("Address", { method: "", //선택 headers: {}, //선택 body: JSON.stringify({}); }) .then() .then() .catch() ~~~
##### fetch():
- Contains the destination address, method, request information, etc.
- Receives the API address, which is a **required** parameter - http://주소 or domain address*with port number), endpoint
###### method
- The method defaults to GET, but POST, PUT, DELETE, etc. can be used and is optional.
###### headers
- Content-Type: "application/json" is primarily used
###### body
- Not used in GET methods - Must be serialized using JSON.stringify before use
- **then()**: Sets the data format to receive - Receives the response, parses it using the json() method, and returns the resulting JSON value.
- **then()**: Where the actual data is stored - Receives the returned JSON value and allows processing as desired
<br><br><br><br><br><br><br><br><br><br><br>
------
References
[What is the difference between synchronous and asynchronous?](https://won-percent.tistory.com/150)
[[React] Async & Await란?](https://narup.tistory.com/216)
[AXIOS Installation & Features & Syntax 💯 Guide](https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-%EC%84%A4%EC%B9%98-%EC%82%AC%EC%9A%A9)
[Mastering JavaScript Promise Concepts & Syntax](https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-%EB%B9%84%EB%8F%99%EA%B8%B0%EC%B2%98%EB%A6%AC-Promise)
[Ajax - Concepts and Usage (Synchronous, Asynchronous)](https://sjparkk-dev1og.tistory.com/27)
[[React] axios 와 fetch 차이점](https://velog.io/@sunkim/React-axios-%EC%99%80-fetch-%EC%B0%A8%EC%9D%B4%EC%A0%90)
[[React] Async & Await란?](https://narup.tistory.com/216)
[Learn How to Use JavaScript fetch().then](https://velog.io/@journy002/%Understanding JavaScript fetch().then() - fetch.then() Usage Guide-How to Use fetch.then() in JavaScript)
Found an error?
Open an issue on GitHub
Corrections will be incorporated with attribution.
Found a typo?
Fork, modify and open a PR.