12.비동기 처리의 시작 콜백 이해하기
1. 동기(synchronous)와 비동기
-
동기적 : 호이스팅 된 이후에 코드가 작성한 순서에 맞춰서 시작된다.
-
자바스크립트는 동기적이다.
-
호이스팅 : 함수나, 변수선언시 자동적으로 제일 위로 올라가는 현상
-
console.log("1");
console.log("2");
console.log("3");
//result 1,2,3
- 비동기적 : 언제 코드가 실행될지 예측 할수가 없음
console.log("1");
setTimeout(() => console.log("2"), 1000);
console.log("3");
//result 1,3,2
2. 동기적으로 작동하는 콜백
function printImmediately(print) {
print();
}
printImmediately(() => console.log("hello"));
3. 비동기적으로 작동하는 콜백
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => consol.log("async callback"), 2000);
4. 콜백 지옥 체험
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === "ellie" && password == "dream") ||
(id === "coder" && password === "academy")
) {
onSuccess(id);
} else {
onError(new Error("not found"));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === "ellie") {
onSuccess({ name: "ellie", role: "admin" });
} else {
onError(new Error("no access"));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage.loginUser(
id,
password,
(user) => {
userStorage.getRolesuser(
user,
(userWithRole) => {
alert(
`Hello" ${userWithRole.name}, you have a ${userWithRole.role} role`
);
},
(error) => {
console.log(error);
}
);
},
(error) => {
console.log(error);
}
);
이 코드의 문제점
-
가독성이 떨어진다.
- 문제가 생길때 수정하기가 어렵다.
-
유지보수가 어렵다.
Leave a comment