JavaScript
async await
KimJye
2019. 7. 23. 20:34
callback이나 promise와 같이 비동키 코드를 작성하는 새로운 방법
Promise chain
function getData() {
return promise1()
.then(response => {
return response;
})
.then(response2 => {
return response2;
})
.catch(err => {
//TODO: error handling
// 에러가 어디서 발생했는지 알기 어렵다.
});
}
Async / Await chain
async function getData() {
const response = await promise1();
const response2 = await promise2(response);
return response2;
}
Async / Await이 Callback이나 Promise보다 나은 점
- 자바와 같이 동기적 코드 흐름으로 개발이 가능하다.
- 코드가 간결해지고, 가독성이 높아진다.
- 응답데이터로 들어오는 변수(관례적으로 많이 사용되는 data, response)를 없앨 수 있다.
- try / catch로 에러를 핸들링할 수 있다.
- error가 어디서 발생했는지 알기 쉽다.
Reference