💻 Programming

async/await

Async Await

Syntax for writing asynchronous code as if it were synchronous. Supported in JavaScript, Python, and Rust. Promise-based.

📖 Detailed Explanation

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.

💻 Code Example

JavaScript
// 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));

🗣️ Examples of Practical Conversations

Senior developer
"How about refactoring this API call section with async/await? The then chaining is three levels deep, so it's hard to read."
Junior Developer
"I agree. However, for the part that calls multiple APIs sequentially, using it together with Promise.all seems like it would also improve performance."
Senior developer
"Good idea. Let's bundle the requests that can be processed in parallel with Promise.all, and handle only the dependent requests sequentially with await."
Interviewer
"Could you explain the difference between async/await and Promise.then(), and tell me in which situations you use each?"
Candidate
"Both deal with Promises, but async/await reads like synchronous code, so it offers good readability in complex flows. On the other hand, then() can be more concise for a simple single asynchronous operation or when used with array methods."
Interviewer
"What happens if you return a Promise inside an async function without await?"
Candidate
"The Promise is automatically unwrapped and returned. Since an async function always returns a Promise, it is handled as a single Promise rather than being nested."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"If you use await inside this for loop, each request runs sequentially. If the requests are independent of each other, it would be better to process them in parallel with Promise.all."
Author
"Ah, you're right. If I build an array of Promises with map and wrap it in Promise.all, it will be much faster. I'll fix it."
Reviewer
"Also, please add error handling. If the rest must still be processed even when one fails, consider Promise.allSettled."

⚠️ Cautions

🔗 Related Terms

📚 Learn More