TIL. async await

FE_JACOB 👨🏻‍💻·2021년 8월 20일
0

Today I learned

목록 보기
21/30

항상 fetch 만 사용하다가 이번에는 async await 를 사용해봤다.

promise 와 then 을 쉽게 만들어주는 ES8 문법이다.

우선 async 선언 방법은 function 앞에 써주거나 arrow function앞에 사용해주면 된다.

//example 1

async function 함수 () {
	//코드자리
}

//example 2 

const 함수 = async() =>{
	//코드자리	
}

원래대로라면 함수안에 코드를 작성하고

함수.then().catch() 

이렇게 사용하지만 await 는 then()을 사용하지 않을 수 있다.

await 는 내가 선언한 어떤 함수가 다 실행될때까지 기다렸다가 실행이 완료되면 그때서야 실행이 된다.

말이 좀 어려운데 내가 직접 사용한 login 할때 함수를 작성해본다.

  1. try catch
  2. await
  3. res
  4. axios

여기서 사용한 4가지이다
1. try는 성공했을때 실행할 코드 catch는 실패했을때의 실행할 코드
2. await 는 post 요청을 res라는 상수에 넣어주고 post 요청을 완료할때까지 기다린다.
3. res는 성공했을 때 조건문으로 그 다음에 실행하고 싶은 코드를 넣어준다.
4. axios 는 라이브러리로 리액트에서 주로 사용을 하고 JSON 데이터에 대한 자동 변환을 해주고 Promise API 지원한다. 자세한 내용은 다음에 작성하도록 하겠다.

const fetchLogin = async () => {
    const { employee_number, password } = userInfo;

    try {
      const res = await axios.post(
        `${BASE_URL}/users/signin`,
        {
          employee_number,
          password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );
      if (res) {
        localStorage.setItem('token', res.data.token);
        history.push('/calendar');
      }
    } catch (err) {
      switch (err.response.status) {
        case 401:
          alert('You do not have permission to access.');
        default:
          alert('Please check the employee number and password.');
          break;
      }
    }
  };

이 코드를 작성하기전엔 공부를 안하고 코드만 무작정 쳤었다.
그리고 그 코드는 async await 가 아니었다.

그때 작성한 코드

const fetchLogin = async () => {
    const { employee_number, password } = userInfo;

    try {
      const res = await axios.post(
        `${BASE_URL}/users/signin`,
        {
          employee_number,
          password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      ).then(res => {
        localStorage.setItem('token', res.data.token);
        history.push('/calendar');
      } 
    }
  };

정확히 기억은 안나지만 이런식이었다. 물론 작동은 하지만 async await 가 아니었다.
const res 로 저장해둔 await promise 를 사용한게 아닌 post 요청을하는 코드였다.
즉, await 가 되지않았다.

profile
단순히 개발자로서 제게 있었던 일을 적는 공간입니다 ✍🏻

0개의 댓글