1. 동기와 비동기
- JavaScript is synchronous 자바스크립트는 동기적이다.
- 호이스팅 된 이후 코드는 작성된 순서에 맞춰 하나하나 동기적으로 실행된다.
- 호이스팅은 var, function 선언이 제일 위로 올라가는 것
- asynchronous는 비동기적, 언제 호출될지 모른다는 의미이다.
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');
- setTimeout이라는 함수 안에 하나의 인자로 만든 함수를 전달해주면 1초 뒤에 부른다는 의미에서 callback
- callback도 즉각적으로 실행하는 synchronous callback과 아닌 asynchronous callback 두 종류로 나눠진다.
2. 동기적 callback
function printImmediately(print){
print();
}
printImmediately(() => console.log('hello'));
3. 비동기적 callback
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'), 2000);
4. callback hell 콜백지옥
class UserStorage{
loginUser(id, password, onSuccess, onError){
setTimeout(()=>{
if(
(id === 'emma' && password === 'Emma') ||
(id === 'coder' && password === 'Coder')
) {
onSuccess(id);
} else{
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if(user === 'emma'){
onSuccess({name: 'emma', 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.getRoles(
user,
userWithRole => {
alert(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
);
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
);
- 콜백함수를 연속해서 쓰면 가독성이 떨어지고 한 눈에 알아보기가 어려우며 디버깅을 해야할 때 매우 어렵다.