5. React, Javascript - axios 와 await , async

JJo·2021년 6월 3일
6

React + SpringBoot

목록 보기
6/12

시작

오늘은 React에서 많이 사용하는 비동기 통신 라이브러리 axios
Javascript 에서 비동기 처리 패턴async,await 에 대해서 알아 보도록 하겠습니다.

1. Axios

Axios ?

Axios 는 Javascript 라이브러리 중 하나인 Fetch Api 와 같은 비동기 통신 라이브러리 입니다.

React 에서는 Axios 를 더 많이 사용하는 경향을 보입니다.
FetchAxios 의 차이점은 Axios 는 요청과 응답을 모두 JSON 형식으로 자동으로 변환시켜 줍니다. 또 FetchBody 속성은 Axios 에서 Data 속성으로 사용되는데 stringify()되어 사용 됩니다.

이러한 Axios 특성으로 인해 많은 사람들이 선호하고 있습니다 !

Axios 사용법

Axios 사용하여 통신하면서 많이 쓰이는 Method 방식에 대해 봅시다.

HTTP 통신 Method 와 동일한 Method 입니다 !

1. GET

  • 서버로 부터 데이터를 받아올때(Get) 주로 사용된다.
  • HTTP 통신 할때 주소에 있는 쿼리스트링을 사용해서 정보를 전달 할 수 있다.
const axios_get = () => {
        axios.get("http://localhost:8080/get")
            .then((response)=> {
                console.log(response);
            })
            .catch((error)=> {
                console.log(error);
            })
    }

axios.get() 함수를 이용해서 GET Method 를 간단하게 사용할 수 있습니다.
axios.get(url,[,config])
.then() 을 통해서 통신에 성공했을때 response가 반환되고 .catch() 를 통해서 통신 실패 했을때 error가 반환됩니다.

2.POST

  • 서버로 데이터를 전송하여 자원(Resource)를 생성(Create) 할 때 사용한다.
  • JSON 형식이나, 객체 형식으로 데이터를 전송 할 수 있습니다.
const axios_post = () => {
        const data = {
            name : 'name',
            age : 23
        }
        axios.post("http://localhost:8080/post", data)
            .then((response)=> {
                console.log(response)
            })
            .catch((error)=> {
                console.log(error)
            })
    }

axios.post() 함수를 이용해서 POST Method 를 간단하게 사용할 수 있습니다.
axios.post(url,data, [,config])

3. PUT

  • 서버에 존재하는 Database 자원을 수정(Update) 하는데 사용한다.
const axios_put = () => {
        const data = {
            age : 25
        }
        axios.put("http://localhost:8080/put", data)
            .then((response)=> {
                console.log(response);
            })
            .catch((error)=> {
                console.log(error);
            })
    }

axios.put() 함수를 이용해서 PUT Method 를 간단하게 사용할 수 있습니다.
axios.put(url, [data], [,config])

4. Delete

  • 서버에 존재하는 Database 자원을 삭제(Delete) 하는데 사용한다.
const axios_delete = () => {
        axios.delete("http://localhost:8080/delete")
            .then((response)=> {
                console.log(response);
            })
            .catch((error)=> {
                console.log(error);
            })
    }

axios.delete() 함수를 이용해서 Delete Method 를 간단하게 사용할 수 있습니다.
axios.delete(url, [,config])

2 . async , await

async & await 는 자바스크립트에서 가장 최근에 등장한 비동기 처리 패턴입니다.

async & await 를 통해서 Promise 를 편하게 사용 할 수 있습니다.

async ?

async 키워드는 함수 의 앞에 붙어서 사용됩니다. async 를 사용하게 되면 함수를 항상 Promise 를 반환하게 됩니다.
만약 반환값이 Promise 가 아니라면 이행상태의 Promise(Resolved Promise) 형태로 값을 감싸 반환되게 됩니다.

const async = async () => {
        return "test";
    }

    console.log(async());
    async().then((data) => {
        console.log(data);
    })

Promise 형식으로 반환 되고 이행상태의 Promise 가 반환되어 .then() 을 이용하여 처리 결과를 받을 수 있습니다.

await ?

await 키워드는 async 함수 안에서만 사용 할 수 있습니다. 함수 안에서 await 를 만나게 되면 Promise 가 처리(Settled) 될 때까지 대기합니다. await 를 이용하게 된다면 콜백함수 처리 없이 비동기 처리를 해줄 수 있습니다.

async & await

이제 async & await 을 사용한 예제를 살펴보겠습니다.

async & await 을 사용한 함수와 그렇지 않은 함수를 만들어서 비교 해보도록 하겠습니다.

    const noAsync = () => {
        const array = [1,2,3];
    }

    const fetchEx = new Promise((resolve, reject)=> {
        const array = [4,5,6];
        resolve(array);
    })

    const async = async () => {
        const array_1 = noAsync();
        const array_2 = await fetchEx;
        console.log('array_1', array_1);
        console.log('array_2', array_2);
    }

    async();

noAsync() 함수는 Promise를 반환하지않고 일반 변수를 반환합니다.
fetchEx() 함수는 resolved 된 Promise를 반환합니다.

fetchEx() 함수가 반환한 Promiseawait 을 통해서 PromiseSettled 될때까지 대기하여 , undefined 가 아닌 정상적인 값이 나오는걸 확인 할 수 있습니다.

오늘 배운 axiosasync & await 를 통해서 api 통신을 적절하게 사용 해 봅시다 !

profile
안녕하세용!!!

0개의 댓글