자바스크립트는 동기 언어이다.
호이스팅(hoisting)이 된 이후에 작성된 순서에 맞춰서 동기적으로 실행된다.
hoisting → var, function declaration
// 동기적 실행방법 -> Syncronous 는 1, 2, 3 처럼 정해진 순서에 맞게 코드가 실행되는 것.
console.log('1'); // -동기
console.log('2'); // -동기
console.log('3'); // -동기
// 비동기적 실행방법 -> ASyncronous 는 1, 3, 2 처럼 정해진 순서와 다르게 코드가 실행되는 것.
console.log('1'); // -동기
setTimeout(() => console.log('2'), 1000); // -비동기
console.log('3'); // -동기
callback hell (콜벡지옥 예시)
// CallBack Hell example
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.getRoles(
user,
userWithRole => {
alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`);
},
error => {
console.log(error);
}
)},
error => {
console.log(error);
}
);