웹개발(프론트)
async / await
수달찌
2021. 3. 29. 08:35
목차
후후... promise 다음에 바로 Async / await 써버리기!!
이렇게 연계되는 건 바로바로 써주는 게
독자에 대한 배려 아니겠슴까!!
Async / await
Async는 비동기 작업 그 자체인 문법이다.
Async함수 안에 await를 쓰고 비동기 작업을 시작하면,
해당 await 비동기 요청까지만 코드가 진행된 뒤, 다른 작업을 진행한다.
비동기 작업이 끝난 뒤 다시 이어서 Async함수가 재개된다.
이거 모를 때는 플래그를 썼었는데... 플래그 변수 선언이 하나둘씩 늘어갈수록 보기 안 좋다.
초기화도 시켜줘야 하고ㅜ 무엇보다 if문으로 너저분해진다.
function After2s() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
try{
console.log('calling');
const result = await After2s();
console.log(result);
} catch (error) {
console.log(error);
}
}
asyncCall();
//from MDN
해당 코드의 결과를 보면,
먼저 calling이 출력되고, After2s함수를 비동기로 실행한다.
그 뒤 asyncCall 함수에서 빠져나와 다른 코드를 수행하다가,
2초 뒤에 After2s의 반환값이 도착하면
그 결과를 출력한다.
여기서
try {
await function();
} catch (error) {
console.log(error);
}
try catch문을 쓰면 비동기 작업이 실패했을 때 를 알 수 있다.