소개
ES2017에 ‘async/await’가 도입된 이후 비동기 JavaScript 작성이 훨씬 더 직관적이 되었습니다. 이를 통해 개발자는 동기식 구조로 비동기식 로직을 표현할 수 있어 중첩된 Promise 체인(.then().catch())에 비해 코드베이스 가독성이 대폭 향상됩니다.
그러나 이 깔끔한 동기식 구문은 성능 문제와 오류 처리 버그를 숨길 수 있습니다. 이 기사에서는 일반적인 비동기/대기 안티패턴에 대해 알아보고 이를 탄력적인 고성능 코드로 리팩터링하는 방법을 알아봅니다.
안티패턴 1: 불필요한 직렬화(순차 대기)
가장 흔한 실수는 독립적인 비동기 작업을 순차적으로 실행하여 병렬 실행 기회를 놓치는 것입니다.
피해야 할 코드
// Fetching three independent datasets sequentially
async function getUserProfile(userId) {
const user = await fetchUser(userId); // takes 1.0s
const posts = await fetchPosts(userId); // takes 1.5s
const followers = await fetchFollowers(userId); // takes 0.8s
return { user, posts, followers };
}
여기서 fetchPosts는 fetchUser가 완료될 때까지 시작되지 않으며 fetchFollowers는 둘 다에 의해 차단됩니다. 총 실행 시간은 1.0 + 1.5 + 0.8 = 3.3초입니다. 이러한 요청은 서로 종속되지 않으므로 동시에 요청해야 합니다.
리팩터링된 코드(Promise.all 사용)
async function getUserProfile(userId) {
// Fire requests concurrently and wait for all to resolve
const [user, posts, followers] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchFollowers(userId)
]);
return { user, posts, followers };
}
Promise.all을 사용하면 세 가지 가져오기가 동시에 실행됩니다. 총 대기 시간은 가장 긴 요청 기간인 1.5초로 줄어듭니다.
안티패턴 2: 중첩된 try-catch 블록
잠재적인 API 오류를 처리할 때 일부 개발자는 기존 콜백 지옥을 모방하여 비동기 함수 내의 깊은 중첩 패턴으로 되돌아갑니다.
피해야 할 코드
async function processData() {
try {
const rawData = await fetchData();
try {
const parsedData = await parseData(rawData);
try {
await saveToDatabase(parsedData);
} catch (dbError) {
console.error("Database save failed", dbError);
}
} catch (parseError) {
console.error("Parsing failed", parseError);
}
} catch (fetchError) {
console.error("Fetch failed", fetchError);
}
}
깊은 중첩은 async/await의 목적을 무효화하여 기능을 검색하고 유지 관리하기 어렵게 만듭니다.
리팩터링된 코드
파이프라인 중에 오류를 포착하려면 전체 흐름을 단일 최상위 try-catch 블록으로 래핑하세요. 특정 오류를 고유하게 처리해야 하는 경우 이를 catch 블록 내에서 분류하거나 ‘.catch()’ 핸들러를 개별 Promise에 연결하세요.
async function processData() {
try {
const rawData = await fetchData();
const parsedData = await parseData(rawData);
await saveToDatabase(parsedData);
} catch (error) {
// Handle or categorize errors centrally
handleProcessingError(error);
}
}
안티패턴 3: Array.prototype.forEach() 내에서 비동기 콜백 사용
비동기 콜백과 함께 ‘forEach’를 사용하면 구문 오류 없이 컴파일되지만 비동기 작업은 순서대로 실행되지 않습니다.
피해야 할 코드
// Iterating and sending emails asynchronously
async function sendEmails(users) {
users.forEach(async (user) => {
await mailer.send(user.email);
});
console.log("All emails queued or sent!"); // <- Executes before mails actually finish sending!
}
Array.prototype.forEach는 콜백 함수에서 반환된 Promise의 해결을 기다리지 않습니다. 모든 콜백을 동기식으로 실행합니다. 결과적으로 후속 로그 문은 이메일이 실제로 수신자에게 도달하기 직전에 인쇄됩니다.
리팩터링된 코드(for…of 또는 Promise.all 사용)
작업을 순차적으로(하나씩) 실행해야 하는 경우:
async function sendEmailsSerially(users) {
for (const user of users) {
await mailer.send(user.email); // awaits each send
}
console.log("All emails sent successfully.");
}
작업을 동시에 실행해야 하는 경우:
async function sendEmailsInParallel(users) {
const promises = users.map(user => mailer.send(user.email));
await Promise.all(promises); // waits for all promises to resolve
console.log("All emails sent successfully.");
}
안티패턴 4: wait 키워드가 없는 비동기 함수
동기 작업만 포함된 함수를 ‘async’로 선언하는 것은 불필요한 성능 저하입니다.
피해야 할 코드
// Simple synchronous math calculation
async function calculateSum(a, b) {
return a + b;
}
함수 앞에 async를 붙이면 런타임 엔진이 자동으로 반환 값을 해결된 Promise로 래핑합니다. 이는 약간의 런타임 오버헤드(마이크로태스크 대기열 예약 및 메모리 할당)를 추가합니다. 함수 내부에 await가 없으면 동기를 유지하세요.
결론
Async/await는 비동기 JavaScript 작성을 위한 우아한 구문을 제공하지만 여전히 내부적으로는 Promise를 기반으로 구축됩니다. 다음 규칙을 염두에 두십시오.
Promise.all을 사용하여 독립적인 작업을 결합합니다.- 비동기 콜백에는
forEach를 사용하지 마세요. 대신for...of또는Promise.all을 사용하세요. - 코드를 읽기 쉽고 디버그하기 쉽게 유지하려면 중첩된
try-catch블록을 피하세요.

