
// Promise 방식
function getData() {
return fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}
// Async/Await 방식
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
주요 차이점:
1. 가독성
에러 처리
여러 작업 처리:
// Promise 방식
function getMultipleData() {
return Promise.all([
fetch('/api/data1'),
fetch('/api/data2'),
fetch('/api/data3')
])
.then(responses => Promise.all(responses.map(r => r.json())))
.then(([data1, data2, data3]) => {
console.log(data1, data2, data3);
});
}
// Async/Await 방식
async function getMultipleData() {
try {
const [response1, response2, response3] = await Promise.all([
fetch('/api/data1'),
fetch('/api/data2'),
fetch('/api/data3')
]);
const [data1, data2, data3] = await Promise.all([
response1.json(),
response2.json(),
response3.json()
]);
console.log(data1, data2, data3);
} catch (error) {
console.error(error);
}
}
// Promise 방식의 로그인
function login(username, password) {
return fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ username, password })
})
.then(response => response.json())
.then(user => {
return fetch(`/api/profile/${user.id}`)
.then(response => response.json())
.then(profile => ({
user,
profile
}));
})
.catch(error => {
console.error('로그인 실패:', error);
throw error;
});
}
// Async/Await 방식의 로그인
async function login(username, password) {
try {
const userResponse = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ username, password })
});
const user = await userResponse.json();
const profileResponse = await fetch(`/api/profile/${user.id}`);
const profile = await profileResponse.json();
return { user, profile };
} catch (error) {
console.error('로그인 실패:', error);
throw error;
}
}