공부블로그

axios로 받아온 값 리턴하기 본문

공부하기

axios로 받아온 값 리턴하기

떠어영 2022. 12. 8. 14:45

 

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