JavaScript asyncawait

정의:

사용 이점:

asyncawait를 사용하면 비동기 코드를 마치 동기 코드처럼 읽고 작성할 수 있습니다. 이는 코드의 가독성과 유지보수성을 향상시킵니다.

기본 사용법:

async function fetchData(url) {
    const response = await fetch(url);
    const data = await response.json();
    return data;
}

fetchData('<https://api.example.com/data>')
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

fetch와 함께 사용하는 사용사례:

사용자 정보와 게시물 가져오기:

async function getUserAndPosts(userId) {
    const userResponse = await fetch(`/api/users/${userId}`);
    const user = await userResponse.json();

    const postsResponse = await fetch(`/api/users/${userId}/posts`);
    const posts = await postsResponse.json();

    return {
        user,
        posts
    };
}

getUserAndPosts(1)
    .then(data => {
        console.log('User:', data.user);
        console.log('Posts:', data.posts);
    })
    .catch(error => {
        console.error('Error fetching user and posts:', error);
    });

에러 처리:

비동기 함수에서 발생할 수 있는 예외를 처리하기 위해 try/catch 블록을 사용할 수 있습니다.

async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Fetching error:', error);
        throw error;
    }
}

결론: