es2017에서는 promise 사용을 더 쉽게 하기 위해 async/await 문법을 도입했다. async/await을 사용하면 비동기 작업을 더 직관적으로 처리 할 수 있다.
먼저 async
로 비동기 함수를 정의하면 그 함수는 await
구문을 사용할 수 있다. 의미 그대로 await
사용하면 promise가 resolve 될때 까지 기다려 주고 resolve된 값을 리턴한다.
const promise = function(val, time) {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(val);
}, time);
});
};
async function asyncFunc() {
const a = await promise(2, 2000);
console.log(a);
const b = await promise(1, 1000);
console.log(b);
}
asyncFunc();
//2
//1
async 함수의 리턴 값은 항상 promise이기 때문에 원한다면 then
을 이용해 비동기 작업을 이어나갈 수도 있다.
const promise = function(val, time) {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(val);
}, time);
});
};
async function asyncFunc() {
const a = await promise(2, 2000);
const b = await promise(1, 1000);
const c = a + b;
console.log(c);
return c;
}
asyncFunc().then(result => console.log(result + 1));
//3
//4
async/await
을 이용할때 try/catch
를 사용해 에러를 처리 하는 것이 가능하다.
try/catch
는 자바스크립트에서 제공되는 에러를 핸들링 하기 위한 문법이다. 하지만 try/catch
안에서 비동기 처리시 callback을 사용하면 try/catch
는 에러를 잡아내지 못한다.
promise에서는 .catch
메서드를 통해 에러를 처리 할 수 있지만 프로미스 체인에서 반환된 에러는 어디에서 에러가 발생했는지에 대한 정보를 주지 않는다는 단점이있다.
try
안에 있는 코드에서 에러가 발생하면 에러가 발생한 시점부터의 흐름이 catch
로 넘어가고 에러를 처리한 후 프로그램이 멈추지 않고 다음 코드가 실행된다.
try {
console.log(1);
throw new Error('err!!!!');
console.log(2);
} catch (err) {
console.log(err);
}
console.log(3)
//1
//Error: err!!!!
//3
async function asyncFunc() {
try {
const a = await promise(2, 2000);
const b = await promise(1, 1000);
throw new Error('err!!!!');
console.log(c);
} catch (err) {
console.log(err);
}
}
asyncFunc();
//Error: err!!!!
에러를 잘 잡아낸다.