async-await

Promise Chaining의 문제점

import { useState } from "react";

const fetchAuthorName = (postId: any) => {
  return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    .then((response) => response.json())
    .then(({ userId }) => {
      return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`).then((response) => response.json());
    });
};

const getUserName = (setData: any) => {
  return fetchAuthorName(1)
    .then(({ name }) => {
      setData(name);
    })
    .catch((error) => {
      console.log(error);
      throw new Error("Failed to fetch author name.");
    });
};

export default function App() {
  const [data, setData] = useState("");
  getUserName(setData);
  return <div>{data}</div>;
}

App 컴포넌트에서 data를 화면에 뿌리기 까지는 6가지 단계를 거친다.

1-4의 단계를 확인할 때 유저의 데이터를 받기 까지 너무 많은 Promise Chaining이 발생하며, 마치 callback hell과 같은 느낌을 받게 된다.

Promise Chaining의 문제점은 다음과 같다.

디버깅

.then((post) => post.user1Id)

Untitled

만약 userIduser1Id로 바꾸었을 경우 다음과 같은 빨간 줄(error)을 확인할 수 있는 데, then 키워드가 워낙 많다 보니 어떤 then에서 에러가 발생하는지 한번에 확인하기 어렵다.

예외 처리

Promise를 사용할 경우 try/catch 대신 catch()를 통해 예외 처리를 해야하는데, 이 경우 동기 코드와 비동기 코드가 섞여 있다면 까다로운 예외 처리를 하게 될 가능성이 생긴다.