동기 : 요청을 보낸 후 해당 요청의 응답을 받아야 다음 동작을 실행하는 방식
비동기 : 요청을 보낸 후 응답과 관계 없이 다음 동작을 실행하는 방식
자바스크립트는 동기적이다. 호이스팅이 된 이후부터 우리가 작성한 순서대로 동기적으로 진행된다.
console.log('1');
setTimeout(() => {
console.log('2');
}, 1000);
console.log('3');
을 예제로 들어보면, 1 → 3 → 2 순서대로 비동기적으로 실행이 된다.
setTimeout과 같은 함수를 콜백 함수라고 한다.
function printImeediately(print) {
print();
}
printImmediately(()=> console.log('hello'));
위의 예제를 추가하면 1 → 3 → hello → 2 순서대로 실행이 된다.
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'), 2000);
위의 예제를 추가하면 1 → 3 → hello → 2 → async callback 순서대로 실행이 된다.
정리를 해보면
function printImmediately(print) {
print();
}
function printWithDelay(print, timeout) {
setTimeout(Print, timeout);
}
console.log('1'); // 동기
setTimeout(()=>console.log('2'), 1000) // 비동기
console.log('3'); // 동기
printImmediately(()=>console.log('hello')); // 동기
printWithDelay(()=>consoele.log('async callback'), 2000); // 비동기
으로 실행된다고 이해하면 된다.
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)}
);
💜 출처 : 드림코딩 by 엘리 https://www.youtube.com/watch?v=s1vpVCrT8f4&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=11 💜