https://third9.github.io/posts/Axios다양하게_활용하기-async_await사용/

Axios를 async/await 를 이용하여 사용하는 방법

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

// 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( () => {
				})
		})
}

위와 같은 형태는 예시이다. 다만 위와 같이 보기에 난잡할 수 있는 코드가 나타날 수 있고, js에서도 async/await 을 이용한 비동기 구문이 추가되었기에 axios도 이를 지원하고 있다.

아래는 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);
  }
}