β¬οΈ Main Note
https://docs.google.com/document/d/14h9Zm7pgkLXctqdm6-bxoeWfAcCxVD5rgprz2-t7hFA/edit
function myCallback() {
const ccc = new XMLHttpRequest(); // new XMLHttpRequest()λ jsμμ μ 곡
ccc.open("get", "http://numbersapi.com/random?min=1&max=200");
ccc.send();
ccc.addEventListener("load", (res) => {
// μ¦ loadκ° λλλ©΄ μ¬κΈΈ μ€νμμΌμ€ μ΄κ±°μ
console.log("λ°μ΄ν°κ° λ‘λλλ©΄ μ΄κ±° μ€νμμΌμ€!");
console.log(res);
const num = res.target.response.split(" ")[0];
const ddd = new XMLHttpRequest(); // new XMLHttpRequest()λ jsμμ μ 곡
ddd.open("get", `http://koreanjson.com/posts/${num}`);
ddd.send();
ddd.addEventListener("load", (res) => {
console.log("λλ²μ§Έλ μ΄κ±° μ€νμμΌμ€!");
console.log(JSON.parse(res.target.response));
const userId = JSON.parse(res.target.response).UserId;
const eee = new XMLHttpRequest(); // new XMLHttpRequest()λ jsμμ μ 곡
eee.open("get", `http://koreanjson.com/posts?userId=${userId}`);
eee.send();
eee.addEventListener("load", (res) => {
console.log("λ§μ§λ§μΌλ‘ μ΄κ±° μ€νμμΌμ€!");
console.log(res.target.response);
});
});
}); // load: request 보λ΄λκ³ response λ°μΌλ©΄ loadλκ³ λμ μ€νμν€κ³ μΆμ ν¨μλ₯Ό λ£μΌλ©΄ λ¨
} // ν¨μλ₯ΌμΈμλ‘ λ£μ΄μ λμ€μ μ€νμμΌμ€ νλκ² callback ν¨μ
new Promise((resolve, reject) => {
// μΈλΆμμ²
// μ€λ걸리λ μμ
=> μΈμ λλ μ§ λͺ¨λ₯΄λκ²λ€μ μ¬κΈ°μ μμ
μ νκ³
resolve("μ² μ");
reject("λ€λμ₯μ΄λ±νκ΅");
})
.then((res) => {
//κ·Έκ² λλλ©΄ μ΄κ±Έ μ€νμμΌμ€
})
.catch((error) => {
// κ·Όλ° λ§μ½ κ·Έ μΈμ λλ μ§ λͺ¨λ₯΄λ μμ
λ€μ€μμ μ€λ₯κ° λλ©΄ μ΄κ±Έ μ€νμμΌμ€
});
function myPromise() {
console.log("1λ² μ€ν");
axios
.get("http://numbersapi.com/random?min=1&max=200")
.then((res) => {
console.log("2λ² μ€ν");
const num = res.data.split(" ")[0];
return axios.get(`http://koreanjson.com/posts/${num}`);
})
.then((res) => {
// promise chaining
console.log("3λ² μ€ν");
const userId = res.data.UserId;
axios.get(`http://koreanjson.com/posts?userId=${userId}`);
})
.then((res) => {
console.log("4λ² μ€ν");
console.log(res.data);
});
console.log("5λ² μ€ν");
}
async function myAsyncAwait() {
const result1 = await axios.get(
"http://numbersapi.com/random?min=1&max=200"
);
const num = result1.data.split(" ")[0];
const result2 = await axios.get(`http://koreanjson.com/posts/${num}`);
const userId = result2.data.UserId;
const result3 = await axios.get(
`http://koreanjson.com/posts?userId=${userId}`
);
console.log(res3.data);
}