자바스크립트 callback
동기와 비동기
'use script'
// JavaScript is synchronous.
// 자바스크립트는 동기적인 프로그래밍 언어이다.
// hoisting: var, function dectaration
// hoisting: 함수 안에 있는 선언들을 모두 끌어올려서 해당 함수 유효 범위의 최상단에 선언하는 것
console.log('1');
setTimeout(()=>console.log('2'),1000); // 브라우저 요청 -> 1초 후 실행
console.log('3');
// 1 3 2 출력
// => 비동기적인 실행 방법
//Synchronous callback (동기)
// 함수의 선언은 호이스팅 되기때문에 제일 위로 가게됨
function printImmediately(print){
print();
}
printImmediately(()=> console.log('hello'));
// Asynchronous callback (비동기)
// 함수의 선언은 호이스팅 되기때문에 제일 위로 가게됨
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
printWithDelay(()=> cosole.log('Async CallBack'),2000); // 제일 마지막에 출력
// callback hell example
// 콜백지옥의 예시
// 아이디가 엘리이고 패스워드가 드림 이거나 아이디가 코더 비밀번호가 아케데미라면 onSucces의 아이디를 불러줌
// 만약 아니라면 not found를 화면에 출력해라 2초뒤 실행
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')); // 에러 'not found'
}
}, 2000);
}
// 사용자가 엘리이면 이름은 엘리고 role 은 어드민인 값을 전달해주고 아니면 not access라고 전달
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'ellie') {
onSuccess({ name: 'ellie', role: 'admin' });
} else {
onError(new Error('no access')); // 에러 'not 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);
}
);
// 콜백함수를 많이쓰면 가독성이 떨어져 이해하기 어렵다.
// 에러가 발생하거나 디버깅을 할때 너무 힘들어..짐 유지보수도 어려움
Last updated
Was this helpful?