본문 바로가기
JavaScript

[JS] async와 await 이해

by watergrace2u 2020. 10. 5.
반응형
SMALL

- 기존의 비동기 처리 방식인 콜백 함수와 프로미스의 단점을 보완하기 위해 사용

- 기본 문법

// 주의: 비동기 처리 메서드가 꼭 프로미스 객체를 반환해야 await가 의도한 대로 동작한다!
async function 함수명() {
  await 비동기_처리_메서드_명();
}

ex1>

// 비동기 처리를 콜백으로 안해도 된다면..
function logName() {
  var user = fetchUser('domain.com/users/1');
  if (user.id === 1) {
    console.log(user.name);
  }
}

// 그냥 콜백으로 처리
function logName() {
  // 아래의 user 변수는 위의 코드와 비교하기 위해 일부러 남겨놓음.
  var user = fetchUser('domain.com/users/1', function(user) {
    if (user.id === 1) {
      console.log(user.name);
    }
  });
}

// 첫 번째 함수에 async, await 적용
async function logName() {
  var user = await fetchUser('domain.com/users/1');
  if (user.id === 1) {
    console.log(user.name);
  }
}

ex2>

function fetchItems() {
  return new Promise(function(resolve, reject) {
    var items = [1,2,3];
    resolve(items)
  });
}

async function logItems() {
  var resultItems = await fetchItems();
  console.log(resultItems); // [1,2,3]
}

fetchItems() -> 프로미스 객체를 반환하는 함수

fetchItems() 함수 실행시 프로미스가 이행되고 결과 값은 items배열이 된다.

logItems() 함수 실행시 fetchItems() 함수의 결과 값인 items배열이 resultItems 변수에 담긴다.

 

ex3>

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();
  });
}

<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);
  }
}

 

cf. joshua1988.github.io/web-development/javascript/js-async-await/

반응형
LIST

'JavaScript' 카테고리의 다른 글

모던 JS 튜토리얼 정리 1  (0) 2020.11.12
[JS] apply 사용  (0) 2020.10.28
[JS] 클로저 주의사항  (0) 2020.10.28
[JS] Fetch API 사용하기  (0) 2020.10.05
[JS] Promise 이해  (0) 2020.10.05

댓글