✔️ 동기적: 정해진 순서에 맞게 코드가 실행되는 것
✔️ 비동기적: 언제 코드가 실행될지 예측할 수 없는 것
console.log('1');
setTimeout(() => console.log('2') ,1000); //비동기적인 실행방법
console.log('3');
콜백이라고 항상 비동기적인 것은 아니다!
function printImmediately(print){
print();
}
printImmediately(() => console.log('hello'));
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'),2000);
class UserStorage {
loginUser(id, password, onSuccess, onError){
setTimeout(() => {
if (
(id === 'somi' && password === 'dream') ||
(id === 'coder' && password === 'academy')
){
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'somi'){
onSuccess({ name: 'somi', role: 'admin' });
}else{
onError(new Error('no access'));
}
}, 1000);
}
}
const userStroage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStroage.loginUser(
id,
password,
user => {
userStroage.getRoles(
user,
userWithRole => {
alert(`hello! ${userWithRole.name}, you have a ${userWithRole.role} role.`)
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
);