async/await
Async Await
Syntax for writing asynchronous code as if it were synchronous. Supported in JavaScript, Python, and Rust. Promise-based.
Async Await
Syntax for writing asynchronous code as if it were synchronous. Supported in JavaScript, Python, and Rust. Promise-based.
async/await is a syntax that lets you write asynchronous programming intuitively, like synchronous code. It is widely supported in modern programming languages such as JavaScript, Python, Rust, and C#, and it solves the problems of callback hell and complex Promise chaining.
The async keyword declares a function as an asynchronous function, and that function always returns a Promise (or the equivalent Future type in the language). The await keyword can be used only inside an async function, and it pauses function execution until the Promise is resolved.
Internally, async/await behaves similarly to a combination of generators and Promises. When it encounters await, it saves the current execution context and hands control over to the event loop. When the Promise completes, execution resumes from the saved point.
Error handling can also use try-catch blocks like synchronous code, which greatly improves code readability. However, because of the nature of asynchronous functions, you must understand the execution order and the way errors propagate precisely in order to prevent unexpected bugs.
// async/await 기본 사용법
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error('사용자를 찾을 수 없습니다');
}
const userData = await response.json();
return userData;
} catch (error) {
console.error('에러 발생:', error.message);
throw error;
}
}
// 여러 비동기 작업 병렬 처리
async function loadDashboard(userId) {
const [user, posts, notifications] = await Promise.all([
fetchUserData(userId),
fetch(`/api/posts?userId=${userId}`).then(r => r.json()),
fetch('/api/notifications').then(r => r.json())
]);
return { user, posts, notifications };
}
// 사용 예시
loadDashboard(123)
.then(data => console.log(data))
.catch(err => console.error(err));
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free