[Javascript] 비동기와 Axios 통신

gongyoon·2022년 6월 16일
0

JS

목록 보기
4/5

지난번에 알아보았던 비동기 작업 패턴을 활용하여 비동기 통신을 알아보려고 한다.

1. Axios란?

fetch Api와 마찬가지로 비동기 통신에 사용되는 라이브러리로 많이 사용되고 있는 비동기 통신 방법이다.

둘은 간단히 비교하자면 이렇다.

fetch api는 간단한 비동기 통신에 axios는 별도의 라이브러리를 설치해야하지만 확장성이 좋아 다양한 지원을 받아 사용이 가능하다.

axios의 파라미터 문법은 이렇다.

axios({
    method: "get", // 통신 방식
    url: "www.naver.com", // 서버
    headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
    params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
    responseType: 'json', // default
    
    maxContentLength: 2000, // http 응답 내용의 max 사이즈
    validateStatus: function (status) {
      return status >= 200 && status < 300; // default
    }, // HTTP응답 상태 코드에 대해 promise의 반환 값이 resolve 또는 reject 할지 지정
    proxy: {
      host: '127.0.0.1',
      port: 9000,
      auth: {
        username: 'mikeymike',
        password: 'rapunz3l'
      }
    }, // proxy서버의 hostname과 port를 정의
    maxRedirects: 5, // node.js에서 사용되는 리다이렉트 최대치를 지정
    httpsAgent: new https.Agent({ keepAlive: true }), // node.js에서 https를 요청을 할때 사용자 정의 agent를 정의
})
.then(function (response) {
    // response Action
});

이제 Promise 방식과 Async & Await 방식을 Axios 통신과 결합해보고자 한다.

Promise 방식의 경우

// then 을 연속적으로 호출하는 예시
const TestApi = () => {
  axios.get('https://test.com/api/v1')
    .then((response) => {
      const data = response.data;
      const userId = data.userId;
      axios.get('https://test2.com/api/v2/' + userId)
        .then((response) => {
          console.log("Response >>", response.data)
        })
        .catch(() => {
        })
    })
    .catch((error) => {
      console.log("Error >>", err);
    })
}

Axios가 Promise를 리턴하므로 then/catch 체인으로 흐름제어가 가능하다. 하지만 then문을 지속적으로 사용할 경우 가독성
이 떨어진다.

Async & Await 방식의 경우

// Async & Await를 사용하는 방식
const TestApi = async () => {
	try{
    	const response = await axios.get('https://test.com/api/v1');
        const userId = response.data.userId;
        
        const response2 = await axios.get('https://test2.com/api/v2' + userId);
        console.log("response >>", response2.data);
    } catch(err) {
     console.log("Error >>", err);
    }
}

Async & Await 를 사용하려면 try/catch문을 사용해야한다. then/catch문에 비하면 간결하고 가독성도 좋아졌다.

💎 참고
Dev Scroll

profile
공부하며 성장하는 사람이 되고 싶은 개발자.

0개의 댓글