반응형

Axios만을 이용하는 경우

axios를 이용하여 API호출을 하는 경우 바로 응답이 오지 않기에 일반적으로 비동기 방식을 사용한다. axios 문서에서도 기본적으로 소개하는 사용방식은 Promise-then 방식의 비동기 호출방식을 소개하고 있다. 다만 then 방식의 경우도 api 호출이 복잡해지면 then을 then 내부에서건 또는 chain 형태로 연달아서 쓰는 경우는 발생한다.

 

즉, Axios만을 이용하면 then을 통해 계속해서 내부로 파고드는 코드가 생기며 코드의 들여쓰기가 이루어져 지저분해지는 현상이 발생하게 되고, catch구문이 많아지면 코드 이해도가 낮아지게 된다.

 

// then 을 연속적으로 호출하는 예시
const TestApiCall = () {
  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);
    })
}

 

 

async/await 를 이용하는 경우

js에서 async/await 를 이용한 비동기 구문이 추가 되었기에 axios도 이를 지원하고 있다. 개인적으로도 async/await 방식을 선호한다.

아래는 async/await 구문을 이용한 방식의 코드이다. 다만 해당 구문에서는 에러처리를 try-catch 방식을 이용해서 작업해야 한다.

// async/await 를 활용하는 수정된 방식
const TestApiCall = 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);
  }
}

 

이전의 then 방식에 비해서 위의 방식이 보기에도 작성하기에도 깔끔하다.

 

 

https://third9.github.io/posts/Axios%EB%8B%A4%EC%96%91%ED%95%98%EA%B2%8C_%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0-async_await%EC%82%AC%EC%9A%A9/#axios%EB%A5%BC-async-await-%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95

 

 

반응형