새싹 프론트엔드

[새싹 프론트엔드] 12/12 (네트워크 통신)

sognociel 2022. 12. 12. 10:24

1. 동기 vs 비동기

동기 방식(synchronous)

  • 요청을 보낸 후 응답을 받아야 다음 동작을 실행할 수 있는 방식
  • 설계가 간단하고 직관적
  • 요청에 대한 응답을 받을 때까지 대기해야 하는 단점
const Sync = () => {
  console.log("1. 안녕하세요");
  console.log("2. 반가워요");
  console.log("3. 안녕히계세요");
  return <div></div>;
};

 

비동기 방식(Asynchronous)

  • 요청을 보낸 후 응답을 받기 전에 다음 작업을 먼저 실행하는 방식
  • 동기 방식보다 복잡함
  • 요청에 대한 응답을 받기까지의 대기 시간에 다른 작업을 할 수 있음
const Async = () => {
  console.log("1. 안녕하세요");
  setTimeout(() => console.log("2. 반가워요"), 3000);
  console.log("3.안녕히계세요");
  return <div></div>;
};

실행 결과

 

 

 

2. async와 await

자바스크립트의 비동기 처리 패턴

 

async | 함수 선언부에 async 키워드 작성

await | async 키워드가 붙어있는 함수 내부에서만 사용 가능하며 결과를 얻을 때까지 대기 (동기방식처럼 처리 가능)

async function 함수이름(){
  await 비동기_처리할_함수 또는 값
}

const 함수이름 = async() => {
  await 비동기_처리할_함수 또는 값
}

 

 

 

3. fetch() 함수로데이터 가져오기

JSONPlaceholder

 

fetch가 비동기임을 알 수 있는 코드. 실행하면 user 데이터가 아니라 undefined가 나온다.

const Fetch = () => {
  const url = "https://jsonplaceholder.typicode.com/users/1";
  let user;

  fetch(url)
    .then((res) => res.json())
    .then((data) => (user = data));

  console.log(user);

  return <div>{user}</div>;
};

 

console.log로 실행순서 확인하기

const Fetch = () => {
  const url = "https://jsonplaceholder.typicode.com/users/1";
  let user;

  fetch(url)
    .then((res) => res.json())
    .then((data) => {
      console.log("1");
      user = data;
      console.log(user);
      console.log("2");
    });

  console.log("3");
  console.log(user);
  console.log("4");

  return

실행 결과

fetch는 비동기 함수이기 때문에 fetch 밖의 console.log가 먼저 실행되는 모습을 볼 수 있다.

 

 

useEffect를 통한 해결

const Fetch = () => {
  const url = "https://jsonplaceholder.typicode.com/users/1";
  const [user, setUser] = useState();

  useEffect(() => {
    fetch(url).then((response) =>
      response.json().then((data) => setUser(data.name))
    );
  }, []);

  return <div>{user}</div>;
};

React에서는 비동기에 대한 처리를 useEffect로 한다.

 

 

'새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 9주차 블로그 포스팅'