개발 공부/JavaScript

220615 [JavaScript] promise와 async,await의 차이점

U_D 2022. 6. 15. 20:42

 

0) 결론

- 코드의 간결함

- 손쉬운 에러 핸들링

- 에러 위치 파악의 용이함

 

1) async는 간결하다

[promise 사용]
then방식을 보면 라인 수가 많은 것은 물론 들여쓰기도 많아 복잡함

function printAnimals() {
  return getAnimals()
    .then(data => {
      if (data.property) {
        return sampleFunc1(data)
          .then(anotherData => {
            console.log(anotherData)
          })
      }else {
        console.log(data)
      }
    })
}

[async/await 사용]
함수에 async 키워드를 적고, 비동기 대상에 await를 추가

비동기 대상 함수에 await를 추가하면, '이 함수의 처리를 기다려!' 라는 의미

async function printAnimals() {
  const animals = await getAnimals();
  if (animals.property) {
    const sampleData = await sampleFunc1(animals);
    console.log(sampleData);
  }else {
    console.log(animals);
  }
}

 

 

2) async는 에러 핸들링에 유리

[promise 사용]
then을 사용하면 내부에 추가적인 catch문을 적어줘야 함
이 방식은 직관적이지 않을 뿐더러 에러를 처리하는 catch문이 중복

function printAnimals() {
  try {
      getAnimals()
      .then((response) => {
      const data = JSON.parse(response); // 여기서 에러 발생한다고 가정
      console.log(data);
    })
    .catch((err)=> {   // 추가적인 에러
      console.log(err)
    })
  }
  catch(err) {
    console.log(err)
  }
}

[async/await 사용]
catch문에서는 try 내부에서 발생하는 모든 에러를 접근할 수 있다.

async function printAnimals() {
  try {
      const data = await JSON.parse((getAnimals())
    console.log(data);
  }
  catch(err) {
    console.log(err)
  }
}

 

 

3) async는 에러 위치를 찾기 쉽다

[promise 사용]
만약 프로미스를 연속으로 호출한다고 가정할 때 어느 지점에서 에러가 발생하면 어떤 then에서 에러가 발생했는지 찾기가 어려움

function sample() {
  return sampleFunc()
    .then(data => return data)
    .then(data2 => return data2)
    .then(data3 => return data3)
    .catch(err => console.log(err))  // 결과적으로 문제가 발생했다
}

[async/await 사용]
async를 사용하게 되면, 어떤 지점에서 에러가 발생했는지 쉽게 찾을 수 있음

async function sample() {
  const data1 = await sampleFunc();      // 문제 발생시 data1값이 유효치 않음
  const data2 = await sampleFunc2(data1);
  return data2;
}

 

 

 

 

*참고 사이트 :
https://demain18-blog.tistory.com/45
https://mong-blog.tistory.com/entry/promise%EC%99%80-async-await%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90