Over the limit
async/awiat을 통한 비동기 처리 본문
서버에서 응답이 돌아오지 않아도 비동기 코드가 실행되도록
async/await을 통해 비동기 코드를 작성해보자.
동기 방식
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);
});
}
해당 코드를 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;
const userResponse = await fetch(
'https://jsonplaceholder.typicode.com/users/${userId}'
);
const user = await userResponse.json();
return user.name;
}
async 키워드가 추가 되었고, 비동기 함수 호출부 앞에 await 키워드도 추가되었다.
이 await 키워드는 async 키워드가 붙어있는 함수 내부 에서만 사용할 수 있으며, 비동기 함수가
리턴하는 promise로부터 결과값을 추출해준다.
Promise 객체 <- 자바 스크립트에서 제공하는, 비동기를 간편하게 처리할 수 있게 도와주는 객체
예외 처리
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 username;
} catch (err) {
console.log("Fail:", err);
return "unknown";
}
}
try/catch 예외 처리는 동기와 비동기 상관없이 가능함
'Network' 카테고리의 다른 글
| 로드 밸런서 Load Balancer란 ? (1) | 2024.08.30 |
|---|---|
| CDN(Content Delivery Network)이란? (0) | 2024.08.30 |
| Apache Kafka란? (0) | 2024.08.27 |
| MQ 메세지 큐란? (0) | 2024.08.27 |
| NTP(Network Time Protocol) (1) | 2024.07.14 |