본문 바로가기
카테고리 없음

[4주차] 보충반 특강2 : 비동기, 동기 (fetch~then, async~await, try~catch~finally)

by whereanna00 2023. 10. 27.

지난 시간

함수와 배열 메소드 복습

 

[4주차] 보충반 특강

// 1. 인자를 3개 받아서, 모든 값을 더해서 출력하는 함수 (출력=>return) var fun01 = function (a, b, c) { return a + b + c; } var fun01 = function (a, b, c) { const result = a + b + c; return result; } // 사용방법 fun09(1,1,1); //

whereannalee.tistory.com

for, forEach 반환값은 없다

map, filter(리턴문에 true 또는 false가 들어감), find 새배열로 반환값이 있다.

 


오늘 배운 것

동기와 비동기, 비동기를 동기화 하기

비동기 = 순서대로 위에서부터 아래로 순차적으로 진행

동기 = 순서 컨트롤 (일에 절차를 부여)

  • 일에 절차가 필요하다면 무조건 then 또는 await 을 떠올려야 한다.
  • 동기 작업 = request에 대한 후행처리가 필요하다는 뜻

 

비동기를 동기화 하기?

외부에 요청하는 것은 무조건 동기적으로 표현하는 것이 좋다.

 


fetch ~ then 

**fetch는 노드환경이 아닌 브라우저 환경에서만 돌아가는 함수이다.

**가짜 서버를 이용하고 싶다면? https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. Serving ~2 billion requests each month.

jsonplaceholder.typicode.com

fetch('https://jsonplaceholder.typicode.com/todos/1', { id: 1, name: "jay"})
      .then(function(response){
        if (response.~~~ === "success"{
          alert("성공");
        }) else {
          alert("실패");
        }
        return response.json(); //한번더 가공하는 작업 -> 하지만 나중에는 axios 툴을 사용할 예정이기 떄문에 크게 중요하지 않음
      }).catch(function(input){
        alert("timeout");
      }); // 예외의 상황에 대한 대응


      // .then(response => response.json())
      // .then(json => console.log(json))

fetch('url', secondInput)// 두번째 인자에 option이 들어감. 
    .then(function(response){
      if (response === "success"){
        alert("성공");
      } else {
        alert("실패");
      }
    }).catch(function(input){
      alert("timeout");
    })

async ~ await

fetch~then 보다는 async~await을 더 많이 쓴다.

만약 1번데이터 저장 후 -> 2번데이터 저장 후 -> 3번데이터 저장 순으로 fetch~then으로 작업하면 콜백지옥에 이를 수 있다.

그래서! 별도의 async 함수를 만들어 await로 호출한다

 

**await는 이 단어가 있는 줄을 기다리라고 하는 의미

 

const result1 = fetch("https://jsonplaceholder.typicode.com/todos/1"); //회원가입

if (result1.code === "성공"){
  alert("성공");
}

// 위처럼 이렇게 쓰게 되면, 죽었다 깨어나도 성공얼러트를 받을 수 있다.

const result2 = await fetch("https://jsonplaceholder.typicode.com/todos/1"); // 너는 무조건 기다려라

if (result2.code === "성공"){
  alert("성공");
} else {
  alert("실패");
}
// fetch -> await 으로 바꿔보기
fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))

// 바꾸기
const result1 = await fetch('https://jsonplaceholder.typicode.com/todos/1'); // 데이터 요청 및 가져오기
const result2 = await result1.json(); // 데이터 가공
console.log('result2', result2);
// async 블럭 안에 await이 있다.
const funnc01 = async function () {
  // (1) 데이터 1 받아오기
  const result1 = await fetch('hhh//~');
  // (2) 데이터 2 받아오기
  const result2 = await fetch('hhh//~', result1);
}

// 위 코드를 아래 화살표함수로 변환하면?

const fun02 = async() => {
  await fetch('http..~');
}

func01();
func02();

try ~ catch ~ finally

fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))
      .catch();

      //catch는 어떤 문제가 생겼을 때 처리하는 영역


// 예시를 보자 아래!
// 이 경우 catch 를 넣어보면?
// try 나한테 제어권이 없는것에 대한 시도~catch 문제를 잡고~finally 마침내


      const funnc01 = async function () {
        try {
              const result1 = await fetch('hhh//~');// (1) 데이터 1 받아오기
              const result2 = await fetch('hhh//~', result1);// (2) 데이터 2 받아오기
        } catch (error) { // 오류내용을 담은 객체인 error가 인자로 들어감
              console.log("알 수 없는 오류가 발생했다.");
              // 오류 데이터 수집하는 로직
        } finally { // 성공과 실패 여부의 상관없이 무조건 실행된다.
              //성공 또는 실패 데이터 적재
        }
      
      }
      
      func01();

 

728x90
반응형