동기: 서버 컴퓨터가 작업이 끝날 때까지 기다리는 통신
비동기: 서버 컴퓨터가 작업이 끝날 때까지 기다리지 않는 통신
서버에 요청 저장이 될 때까지 기다리지 않고 다른 작업 실행
(ex 게시물 목록 가져오기, 상품 목록 가져오기, 게임 다운 받으면서 카톡하기)

[VSCODE에서 비동기]
//비동기 통신
function 함수이름() {
const data = axios.get('https://koreanjson.com/posts/1')
console.log(data) // Promise
}
axios를 사용하여 비동기 통신을 사용
axios가 data를 주겠다고 약속만 한 상황인데 바로 다음 줄이 실행이 되어 버린다.
[비동기를 동기로 바꿔주는 명령어]
async/await
//동기 통신
async function 함수이름() {
const data = await axios.get('https://koreanjson.com/posts/1')
console.log(data) // {id: 1, title: "정당의 목적이나 활동이 ...", ...}
}
await를 붙이면 "axios.get이 끝날 때까지 이 줄에서 기다려"하는 뜻이 된다.
await를 붙이면 async를 짝으로 붙여줘야한다.
import axios from 'axios'
export default function RestGetPage(){
function callRestApi() {
const result = axios.get("https://koreanjson.com/posts/1")
//get=메서드 endpoint= posts/1
console.log(result)
}
return (
<div>
<button onClick={callRestApi}>REST-API 요청하기!!!</button>
</div>
)
}
실행했을 때 Promise {} 라는 결과만 나온다.
import axios from 'axios'
export default function RestGetPage(){
**async** function callRestApi() {
const result = **await** axios.get("https://koreanjson.com/posts/1")
//get=메서드 endpoint= posts/1
console.log(result)
}
return (
<div>
<button onClick={callRestApi}>REST-API 요청하기!!!</button>
</div>
)
}
async 와 await를 추가하면
{data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
결과가 나온다.
console.log(child)
var child = "철수"
->undefined
자바스크립트는 위에서 한 줄씩 실행이 되므로 철수가 먼저 정의되지 않아 에러가 나야 정상
console.log(child3)
const child3 = "철수"
-> 에러
console.log(child3)
let child3 = "철수"
-> 에러
따라서 잘 var은 사용하지 않는다!
[var의 실행과정]
console.log(child)
var child = "철수"
var child = undefined;
console.log(child)
child = "철수"
호이스팅: 끌어올리다
이런 것을 호이스팅이라고 한다.
const와 let도 호이스팅이 되지만 실제 할당되기 전까지는 접근이 불가능하다.
TDZ(Tempral Dead Zone)에 들어가있기 때문이다.
fuction 값이 중복되어도 실행되므로 화살표 함수를 많이 쓴다.
const callRestApi = async () => {
const result = await axios.get("https://koreanjson.com/posts/1")
//get=메서드 endpoint= posts/1
console.log(result)
console.log(result.data.title)
setData(result.data.title)
}
화살표 함수에서 async의 자리가 이동한다.
[graphql 실습]
_app.js가 1번으로 실행되므로 세팅을 해주어야한다.
import '../styles/globals.css'
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client'
function MyApp({ Component, pageProps }) {
const client = new ApolloClient({
uri:"http://backend06.codebootcamp.co.kr/graphql",
cache: new InMemoryCache()
})
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
)
}