async await

sohyun·2022년 7월 25일
0

드림코딩 강의 정리

목록 보기
20/20

async & await 기본 문법

async function 함수명() {
		await 비동기처리 메서드명();
}
  • 함수 앞에 async 예약어 붙이기
  • 함수의 내부 로직 중 HTTP 통신을 하는 비동기 처리 코드 앞에 await 붙이기
    • 주의‼️ 비동기 처리 메서드가 꼭 프로미스 객체를 반환해야 await가 의도한대로 동작함
    • 일반적으로 await 의 대상이 되는 비동기 처리 코드는 Axios 등
      프로미스를 반환하는 API호출 함수

async & await 실용 예제

function fetchUser() {
  var url = 'https://jsonplaceholder.typicode.com/users/1'
  return fetch(url).then(function(response) {
    return response.json();
  });
}

function fetchTodo() {
  var url = 'https://jsonplaceholder.typicode.com/todos/1';
  return fetch(url).then(function(response) {
    return response.json();
  });
}
  • 각각 사용자 정보와 할 일 정보가 담긴 프로미스 객체가 반환
    • fetchUser()를 이용하여 사용자 정보 호출
    • 받아온 사용자 아이디가 1 이면 fetchTodo() 호출
    • 받아온 할 일 정보의 제목을 콘솔에 출력
async function logTodoTitle() {
  var user = await fetchUser();
  if (user.id === 1) {
    var todo = await fetchTodo();
    console.log(todo.title); // delectus aut autem
  }
}
  • logTodoTitle()을 실행하면 콘솔에 delectus aut autem 가 출력됩니다.
  • 콜백이나 프로미스로 했다면 코드가 길어졌을것이며
    가독성도 좋지 않았을 것입니다.

async & await 예외 처리

  • try catch
async function logTodoTitle() {
  try {
    var user = await fetchUser();
    if (user.id === 1) {
      var todo = await fetchTodo();
      console.log(todo.title); // delectus aut autem
    }
  } catch (error) {
    console.log(error);
  }
}
  • 네트워크 통신 오류 뿐만 아니라 타입 오류등의 일반적인 오류도 catch 로 잡아낼 수 있습니다.
  • 발견된 에러는 error객체에 담기기 때문에 유형에 맞게 에러코드를 처리하면 된다.

Axios , async&await 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
         .text-success {
            color:#0066ff;
            font-size:24px;
        }
    </style>
</head>
<body>
    <div id="loading"></div>
    <h1>Async await</h1>
    <a href="#" id="btn"> load json </a>
    <div id="console"></div>

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        document.querySelector('#btn').addEventListener('click',(e)=>{
            e.preventDefault();
            (async()=>{
                let json = null;
                try{
                    const response = await axios.get('backend/dept_item.json');
                    json = response.data;
                }catch(e){
                console.log(e);
                console.log(e.response.status);
                console.log(e.response.data);
            }
            document.querySelector('#console').insertAdjacentHTML('beforeend',JSON.stringify(json));
            })();
        });
    </script>
</body>
</html>

REF

캡틴판교

profile
냠소현 개발일지

0개의 댓글