-
JS(Async, Await)JS 2022. 3. 23. 17:20
JS 비동기 처리 패턴 중 가장 최근 문법!
☞여러 개의 비동기 처리 코드를 다룰 때 좋다.
☞callback, promise 보다 가독성이 좋다.
사용법
async function 함수() { await 비동기_처리_메서드(); }
1. 함수 앞에 async 예약어 붙이기
2. 함수의 내부 로직 중 HTTP 통신을 하는 비동기 처리 코드 앞에 await 붙이기
예제
function fetchItems() { return new Promise(function(resolve, reject) { const items = [1,2,3]; resolve(items) }); } async function logItems() { const resultItems = await fetchItems(); console.log(resultItems); } ///[1,2,3]
1. fetchItems() 함수를 실행하면 프로미스가 resolved 되며 결과 값은 items 배열이 된다. // [1,2,3]
2. logItems() 함수를 실행하면 fetchItems() 함수의 결과 값인 items 배열이 resultItems 변수에 담긴다 → 콘솔에는 [1,2,3] 출력
※ await를 사용 X → 데이터를 받아온 시점에 콘솔에 출력할 수 있게 콜백 함수나, .then()을 이용해야함
예제2(예외 처리 까지)
: try, catch 사용
function fetchUser() { const url = 'https://jsonplaceholder.typicode.com/users/1' return fetch(url).then(function(response) { return response.json(); }); } function fetchTodo() { const url = 'https://jsonplaceholder.typicode.com/todos/1' return fetch(url).then(function(response) { return response.json(); }); } async function logTodoTitle() { try { const user = await fetchUser(); if (user.id === 1) { const todo = await fetchTodo(); console.log(todo.title); //user 1 의 todo.title 출력 } } catch(error) { console.log(error); } }
참고
https://joshua1988.github.io/web-development/javascript/js-async-await/
'JS' 카테고리의 다른 글
JS9(동기/비동기) (0) 2022.03.17 JS기본(promise) (0) 2022.01.31 JS숫자추측게임1 (0) 2022.01.14 JS (web API's, event) (0) 2022.01.14 JS(this배우기) (0) 2022.01.13