JavaScript async await
— JAVASCRIPT, 2022 — 3 min read
async await
- es2017 도입
- 프라미스 기반의 비동기 코드를 동기적 코드처럼 작성 할 수 있게 합니다.
- await 키워드는 async 키워드로 선언된 함수 안에서만 사용
에러
UnhandledPromiseRejection 에러 메세지 확인
찾아보니
- asnyc/await을 사용한 함수는 promise를 반환한다는 것을 알게되었다.
- async 키워드를 사용한 함수의 경우 try catch 로 애러 핸들안해줘서 발생
then/catch 사용
axios.get('https://api.test.com/data').then((response) => { if (response && response.data){ axios.getget('https://api.test2.com/data').then((res) => { setData({ classification:res.data, donation:response.data }); }); }})
then/catch는 프로미스 체이닝을 사용해서 순차적으로 비동기 작업을 수정할 수 있습니다 첫 요청이 성공하면 다음 요청을 수행
async/await 사용
const load = async () => {
try { const response = await axios.get('https://api.test.com/data'); if (response && response.data) { const res = await axios.get('https://api.test2.com/data'); setData({ classification: res.data, donation: response.data }); } } catch (error) { console.error('Error fetching data:', error); }};
async/await는 비동기 코드를 동기 코드처럼 작성할 수 있어서 직관적 await 을 사용해 프로미스가 해결될 때까지 기다리며 try catch 로 블록을 사용해 에러처리 async/await 디버깅시 스택 트레이스 제공
- async/await 와 then/catch 혼합해서 사용 비추
const load = async () => { try { const response = await axios.get('https://api.test.com/data') .then(response => { // .then 블록 안에서 또 다른 비동기 요청을 처리 return axios.get('https://api.test2.com/data').then(res => { setData({ classification: res.data, donation: response.data }); return res; }); }); } catch (error) { console.error('Error fetching data:', error); }};
await 사용시 비동기 작업을 동기적으로 작성할 수 있어서 마치 동기 코드처럼 보입니다
반면 then 은 비동기 체이닝을 사용한 구문입니다
해당 부분이 코드를 읽는 사람이 혼란스러울 수 있습니다. 두가지 비동기 처리 방식을 이해하고 신경 써야 하기 때문에 가독성을 떨어뜨립니다 try catch 와 then 이후 catch 등 중복 사용된다면 정확히 어디서 에러가 처리되는지 알 수 없습니다