230902.log

Universe·2023년 9월 2일
0

log

목록 보기
7/14
🗓️ 날짜 : 2023.09.02

📚 할 일 : 10to7, 1day 1commit 1post, 1mon 3project

📝 오늘의 목표 : 유튜브 클론코딩 프로젝트, 면접준비

⌛ 공부시간 : 10:00 ~ 15:00

TIL

Promise

function newsInfo() {
 return axios.get("https://api/v2")
}

async function newsInfo2(){
return await axios.get("https://api/v2")
}

이 둘의 차이에 대해서 설명해보세요.
하면 어떻게 대답해야 할까?
생각하다가 간단하게 정리해보려고 한다.

기본적인 차이점

우선, 위의 두 함수의 반환하는 값은 같다.
axios 는 항상 Promise 객체를 리턴하므로 return await 를 하더라도 Promise 객체를 반환한다.
구체적으로는 둘의 후속 처리부분에 초점을 맞추어야 한다.

newsInfo 함수는 axios.get 의 Promise 객체를 “직접” 반환한다.
이 함수 자체가 비동기 함수는 아니지만 반환하는 값이 Promise 이므로
호출하는 곳에서 .then(), catch() 등의 메소드를 사용할 수 있다.

newsInfo2 함수는 async 키워드를 통해 비동기 함수로 정의되었고
await 키워드를 사용하여 axios.get의 반환값을 ‘기다린 후에’ 반환한다.
하지만, 내부 로직을 보면 별도의 처리를 하지 않아 axios.get 의 Promise를 그대로 반환한다.

두드러지는 차이점

두드러지는 차이점은 후속 처리 부분에서 볼 수 있다.
예시는 다음과 같다.

  • async await 를 사용하지 않는 경우
newInfo()
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

가장 기본적인 프로미스 처리 방법으로, then 은 성공시 호출, catch 는 에러 발생시 호출된다.

  • async await 를 사용하는 경우
async function fetchData() {
  try {
    const response = await newInfo();
    console.log(response.data);
  } catch (error) {
    console.log(error);
  }
}

Promise 객체를 처리하기 위해서는 async / await 를 사용하는 쪽이 조금 더 간결하고 가독성이 좋다.
위의 예시로는 크게 와닿지 않는데, 비동기 로직을 순차적으로 처리할 때 효과적이다.

아래의 두 함수가 있다고 가정해보자.

function fetchUser() {
  return axios.get('https://api/v2');
}

function fetchPosts() {
  return axios.get(`https://api/v2`);
}

유저 데이터를 불러온 다음, Post 데이터를 불러와야 한다면,

  • then() 과 catch() 를 사용한 순차적 비동기 로직
fetchUser()
  .then(response => {
    const userId = response.data.id;
    return fetchPosts(userId);
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
  • async / await 를 사용한 순차적 비동기 로직
async function fetchData() {
  try {
    const userResponse = await fetchUser();
    const userId = userResponse.data.id;
    const postsResponse = await fetchPosts(userId);
    console.log('Posts:', postsResponse.data);
  } catch (error) {
    console.log('An error occurred:', error);
  }
}

fetchData();

.then(), .catch() 를 사용한 코드는 여러겹의 체인을 이루고 있기 때문에
로직이 복잡해지면 코드의 가독성을 크게 저하시킨다.

반면에 async/await 를 사용하면 비동기 로직을 동기적인 코드처럼 작성할 수 있기 때문에
코드의 가독성이 굉장히 좋다. 또한 에러핸들링도 try, catch 블록을 사용하여
조금 더 명확하게 할 수 있다.

Promise.all

그렇다고 반드시 async / await 가 좋은 것은 아니고,
여러개의 프로미스를 동시에 실행하고, 모든 프로미스가 완료된 이후에 특정 로직을 실행해야 한다면
Promise.all 메소드가 조금 더 효과적일 수 있다.

Promise.all([newInfo(), newInfo2(), newInfo3()])
  .then((responses) => {
    console.log(responses.map(res => res.data));
  })
  .catch((error) => {
    console.log(error);
  });

이런식으로 코드를 구성하면
모든 Promise 가 완료되었을 때만 then 코드 블럭을 실행하기 때문에
모든 호출이 완료된 이후에 특정 로직을 수행할 수 있어 async / await 보다 유용하다.

profile
Always, we are friend 🧡

0개의 댓글