Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- redux
- rebase
- Git
- 컬러구성
- list.map
- 리사이클러뷰
- await
- 자동반영
- 리덕스
- react
- 리액트를 다루는 기술
- typescript
- 웹
- createPortal
- merge
- useCallback
- list
- 리액트
- CSS
- pull
- Kotlin
- 비동기처리
- hot Reloading
- 가상회선교환
- 공부
- javascript
- equalityFn
- php문법
- async
- useState
Archives
- Today
- Total
공부블로그
axios로 받아온 값 리턴하기 본문
await / async → promise의 동작을 동기스럽게 사용할 수 있게 한다 = "비동기(를) 처리"
1. then( )에서 응답 기다리고 return
const getData = () =>{
// 1.
return axios.get('https://api.binance.com/api/v3/ticker/24hr')
// 응답 성공 시, response에 접근 가능
.then((response) => { return response.data })
// 2.
let response = axios.get('https://api.binance.com/api/v3/ticker/24hr')
return response.then(response => response.data )
}
// getData 함수가 비동기적(결과가 바로 나오지 않음)이므로 비동기 처리 필요!!! (async/await)
const wait = async () => {
console.log(getData()) // 틀림! Promise<{Pending}> 출력
console.log(await getData()) // 응답(Promise) 받아올 때까지 기다려주는 await
}
wait()
2. async / await 으로 응답 기다리고 return
const getData = async () => {
//await로 비동기를 처리하지 않으면 response에 접근할 수 없다.
let response = await axios.get('https://api.binance.com/api/v3/ticker/24hr')
return response.data
}
const wait = async () => {
console.log(await getData()) // 비동기 함수 getData를 await
}
wait()
3. try / catch 사용했을 때
const getData = () => {
try {
let res = axios({
url: 'https://api.binance.com/api/v3/ticker/24hr',
method: 'get'
})
return res
} catch (e) {
console.log(e)
}
}
const wait = async () => {
console.log( await getData() ) //비동기 함수를 await해서 동기적으로 처리
}
wait()
'공부하기' 카테고리의 다른 글
list.map( ) (0) | 2022.12.20 |
---|---|
useSelector 최적화 (0) | 2022.12.13 |
아이콘 버튼 만들기 ( styled-component ) (0) | 2022.12.02 |
Typescript 타입, 인터페이스, 함수 (0) | 2022.11.30 |
Git 협업 (1) | 2022.11.25 |