React
비동기 프로그래밍
차돌박이츄베릅
2023. 6. 21. 14:50
비동기 프로그래밍을 만나게 되는 경우
- 서버 통신으로 어떤 값을 얻어온다
- setTimeout, addEventListner한다
- 콜백함수
=> 즉, 제어권이 넘어가게 되는 경우
동기적 방식 : 순차적 실행
Promise 객체에 담기는 주요 상태정보
- 대기(pending) 상태
- 이행(fulfilled) 상태
- 거부(rejected) 상태
Promise 객체 핸들링 방법
then ~ catch (ES6)
axios로 받게 되면 response.data로 데이터 확인할 수 있음
정상인 경우 then, finally 실행
오류인 경우 catch, finally 실행
// http://api.naver.com/weather/today 로 요청을 한다고 가정합시다.
axios.get('http://api.naver.com/weather/today')
.then(response => {
console.log('정상처리 되었습니다 : ' + response);
})
.catch(error => {
console.log('오류가 발생하였습니다 : ' + error);
})
.finally(()=>{
console.log('항상 실행되는 부분입니다!');
});
async / await (ES7)
화살표 소괄호 앞에 async키워드를 줌. 이건 비동기함수가 되는거
비동기 블록{} 안 await를 만나면 그게 끝나기까지 기다렸다가 밑으로 감
await를 비동기 로직(axios.get...) 앞에 써주면 됨
const getWeather = async () => {
try {
const response = axios.get('http://api.naver.com/weather/today');
console.log('정상처리 되었습니다 : ' + response);
} catch (error) {
console.log('오류가 발생하였습니다 : ' + error);
}
}