[JS] async-await / then-catch

냐옹·2023년 8월 30일
0

JS

목록 보기
2/6
post-thumbnail

자바스크립트에서 비동기 작업을 처리하는 방법에는 크게 callback, promise 그리고 그에 따른 (then..catch) 그리고 async-await이 있다.

Promise, then-catch

  • Promise는 자바스크립트에서 비동기 작업의 최종완료 (또는 실패) 와 그 결과값을 나타낸다.
  • then은 Promise의 성공적인 결과에 대한 콜백을 설정한다
  • catch는 Promise에서 발생한 예외나 오류에 대한 콜백을 설정한다.
function asyncFunction(){
	return new Promise((resolve, reject) => {
    setTimeout(()=>{
    	resolve('Success!');
        reject('Error!');
        }, 1000);
    });
 }
 
 asyncFunction().then(result => {
 	console.log(result); // Success! 출력
    })
    .catch(error => {
    	console.error(error);
     });

async-await

  • async-await은 Promise를 더 간결하고 동기식 코드처럼 읽히게 작성할 수 있게 도와줍니다.
  • 함수 앞에 async 키워드가 붙으면 해당 함수는 무조건 항상 Promise를 반환합니다.
  • await 키워드는 Promise의 완료를 기다립니다. await은 async함수 내에서만 사용할 수 있습니다.
async function asyncFunction() {
    return 'Success!';
}

async function executeFunction() {
    try {
        const result = await asyncFunction();
        console.log(result);  // 'Success!' 출력
    } catch (error) {
        console.error(error);
    }
}

executeFunction();

한번 비교해봅시다

가독성

  • async-await이 더 좋아보입니다. 더 직관적이고 동기식 코드와 비슷하게 보이기 때문에 복잡한 로직에서 가독성이 더 좋습니다.

오류처리

  • async-await은 try-catch구문을 사용하여 오류를 처리합니다. 이로인해 전통적인 오류처리 방식과 같은 패턴으로 비동기 오류를 처리할 수 있습니다.

Chaining

복수의 연속적인 비동기 작업이 있을 때 then-catch는 체이닝하기 좋긴하나, async-await도 적절히 사용하면 같은 효과를 낼 수 있습니다.

결론

async await 쓰자

0개의 댓글