2020. 6. 17. 13:26ㆍ웹/Javascript(ES6+)
문법
-
async function 선언은 AsyncFunction 객체를 반환하는 하나의 비동기 함수를 정의
-
비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수, 암시적으로 Promise를 사용하여 결과를 반환
(Promise : async 함수에 의해 반환 된 값으로 해결되거나 async 함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값)
-
await 연산자는 async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료후 값을 반환
-
await 연산자는 async function 내부에서만 사용 가능
async function 함수명() {
await 비동기 메서드명();
}
예제)
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve('success');
}, 1000)
});
}
async function loadData() {
const result = await fetchData();
console.log(result);
};
loadData();
-- 출력결과 --
success
async & await 예외 처리
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve('success');
}, 1000)
});
}
async function loadData() {
try {
const result = await fetchData();
console.log(result);
} catch(e) {
console.log(e); }
};
loadData();
async & await 장점
-
여러 개의 비동기 처리
예제) 사용자 정보를 받아온 뒤, 데이터를 조회하는 예제
// 데이터 조회
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve('fetch Data');
}, 1000)
});
};
// 사용자 정보
function fetchUserInfo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve({
name: 'Lee'
});
}, 1000)
});
};
async function loadData() {
const user = await fetchUserInfo();
if (user.name === 'Lee') {
const data = await fetchData();
console.log(data);
}
};
loadData();
-- 출력결과 --
fetch Data
설명
-
사용자 정보와 데이터 조회하는 프로미스 반환하는 함수 존재
※ Promise 처리
-
콜백함수나 프로미스로 처리 한다면 코드 가 더 길어지며 가독성이 떨어짐
fetchUserInfo().then((user) => {
if (user.name === 'Lee') {
fetchData().then(result => {
console.log(result);
});
}
});
참조
https://joshua1988.github.io/web-development/javascript/js-async-await/
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/await
'웹 > Javascript(ES6+)' 카테고리의 다른 글
비동기 처리 - Promise (0) | 2020.06.16 |
---|---|
iterator 와 for-of (0) | 2020.04.10 |
Rest, Spread 연산자 (0) | 2020.04.09 |
Destructuring(구조 분해 할당) (0) | 2020.04.08 |
템플릿 리터럴 문자열 표현식 (0) | 2020.04.08 |