-
(번역) JavaScript에서 then()과 async/await의 사용 비교Developer 2024. 11. 20. 14:38728x90
핵심 요약
- then(): 비동기 작업 후 콜백 함수를 실행하며, 함수의 나머지 부분은 계속 실행됩니다.
- async/await : 비동기 작업이 완료될 때까지 함수 실행을 일시 중지하여, 동기적인 코드처럼 작성할 수 있습니다.
- 가독성과 유지보수를 위해 async/await 사용이 권장되며, 복잡한 프로미스 체이닝은 피하는 것이 좋습니다.
JavaScript에서 비동기 요청을 처리할 때, then()과 async/await 두 가지 방법을 사용할 수 있습니다.
이 두 방법은 매우 유사하지만, 함수 실행 흐름에서 차이가 있습니다.
async 함수 내에서는 JavaScript가 프로미스가 해결될 때까지 함수 실행을 일시 중지합니다.
반면, then()을 사용할 경우 함수의 나머지 부분은 계속 실행되지만, 프로미스가 해결될 때까지 .then() 콜백은 실행되지 않습니다.
예를 들어, async/await를 사용하는 경우:
async function test() { console.log('Ready'); let example = await fetch('http://httpbin.org/get'); console.log('I will print second'); } test(); console.log('I will print first');
위 코드에서 test() 함수는 'Ready'를 출력한 후, fetch 요청이 완료될 때까지 기다립니다.
그 후 'I will print second'를 출력합니다. 동시에, test() 함수 호출 이후의 코드는 즉시 실행되어 'I will print first'를 출력합니다.
반면, then()을 사용하는 경우:
function test() { console.log('Ready'); let example = fetch('http://httpbin.org/get').then((res) => { console.log('This is inside the then() block'); }); console.log('This is after the fetch statement where we are now executing other code that is not async'); } test(); console.log('this is after the entire function');
이 코드에서는 'Ready'를 출력한 후, fetch 요청이 비동기적으로 처리됩니다.
'This is after the fetch statement where we are now executing other code that is not async'가 즉시 출력되고, fetch 요청이 완료되면 'This is inside the then() block'이 출력됩니다.
마지막으로 'this is after the entire function'이 출력됩니다.
가능한 경우 async/await를 사용하는 것이 좋으며, 프로미스 체이닝은 최소화하는 것이 좋습니다.
async/await는 JavaScript에 익숙하지 않은 개발자들에게도 코드를 더 읽기 쉽게 만들어 줍니다.
출처: https://dev.to/masteringjs/using-then-vs-async-await-in-javascript-2pma
728x90'Developer' 카테고리의 다른 글
(번역) Create React App vs Vite (2) 2024.11.21 (번역) Redux vs Context API: 언제 사용해야 할까 (0) 2024.11.21 Mac M2 도커 설치 (2) 2024.08.30 axios interceptors로 API 요청/응답 핸들링하기 (0) 2024.08.30 내 블로그에 개발자 명언 노출시키기 (0) 2024.06.11