동기 : 서버 컴퓨터가 작업이 끝날 때까지 기다리는 통신.
하나 끝나면 다음 하나를 실행.
비동기: 서버 컴퓨터가 작업이 끝날때까지 기다리지 않는 통신.
서버에 요청(등록, 수정, 삭제 등) 저장이 될 때까지 기다리지 않고 다른 작업을 진행한다.
기존에는 비동기를 동기로 바꿔주려면 Promise를 사용했어야 했다.
그치만 Promise는 then()을 연쇄적으로 호출하고 있어서
어느 then에서 오류가 나오는지 찾기 힘들다
이런 불편한 점을 해결하기 위해 async / await가 나왔다.
비동기를 동기로 바꿔주는 명령어
await를 사용하기 위해선 함수 앞에 asycn를 붙여줘야한다.
function myCallback() {
const aaa = new XMLHttpRequest()
aaa.open("get", "http://numbersapi.com/random?min=1&max=200")
aaa.send()
aaa.addEventListener("load", (res) => {
console.log("데이터가 로드되면 실행시켜줘")
const num = res.currentTarget.response.split(" ")[0]
const bb = new XMLHttpRequest()
bb.open("get", `http://koreanjson.com/posts/${num}`)
bb.send()
bb.addEventListener("load", (res) => {
console.log("bb데이터가 로드되면 실행시켜줘")
const userId = JSON.parse(res.target.response).UserId
const cc = new XMLHttpRequest()
cc.open("get", `http://koreanjson.com/posts?userId=${userId}`)
cc.send()
cc.addEventListener("load", (res) => {
console.log("cc데이터가 로드되면 실행시켜줘")
console.log(res)
})
})
})
}
function myPromise() {
axios.get("http://numbersapi.com/random?min=1&max=200")
.then((res) => {
const num = res.data.split(" ")[0]
return axios.get(`http://koreanjson.com/posts/${num}`)
.then((res) => {
const userId = res.data.UserId
return axios.get(`http://koreanjson.com/posts?userId=${userId}`)
.then((res) => {
console.log(res.data)
})
})
})
}
async function myAsyncAwait() {
const res1 = await axios.get(
"http://numbersapi.com/random?min=1&max=200"
);
const num = res1.data.split(" ")[0];
const res2 = await axios.get(
`http://koreanjson.com/posts/${num}`
);
const userId = res2.data.UserId;
const res3 = await axios.get(
`http://koreanjson.com/posts?userId=${userId}`
);
console.log(res3.data);
}