
원격 REST API를 호출을 하여 게시물 작성자의 이름을 리턴하는 함수를 작성하고 그 함수를 호출해 보자.
function fetchAuthorName(postId) {
return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
.then((response) => response.json())
.then((post) => post.userId)
.then((userId) => {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then((response) => response.json())
.then((user) => user.name);
});
}
fetchAuthorName(1).then((name) => console.log("name:", name));
// name: Leanne Graham
함수 선언부에 async 키워드가 function 앞에 붙는다.
Promise를 리턴하는 모든 비동기 함수 호출부 앞에는 await 키워드가 추가된다.
✅ await 키워드는 async 키워드가 붙어있는 함수 내부에서만 사용할 수 있으며 비동기 함수가 리턴하는 Promise로 부터 결과값을 추출해준다.
✅ 즉, await 키워드를 사용하면 일반 비동기 처리처럼 바로 실행이 다음 라인으로 넘어가는 것이 아니라 결과값을 얻을 수 있을 때까지 기다려준다.
async function fetchAuthorName(postId) {
const postResponse = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postId}`
);
const post = await postResponse.json();
const userId = post.userId;
const userResponse = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const user = await userResponse.json();
return user.name;
}
fetchAuthorName(1).then((name) => console.log("name:", name));
동기/비동기 구분없이 try/catch로 일관되게 예외 처리를 할 수 있는 부분도 async/await를 사용해서 코딩했을 때의 큰 이점 중 하나이다.
async function fetchAuthorName(postId) {
const postResponse = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postId}`
);
const post = await postResponse.json();
const userId = post.userId;
try {
const userResponse = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const user = await userResponse.json();
return user.name;
} catch (err) {
console.log("Faile to fetch user:", err);
return "Unknown";
}
}
fetchAuthorName(1).then((name) => console.log("name:", name));