본문 바로가기
javascript

callback

by rami_ 2022. 2. 1.

1. Synchronous callback(동기) vs Asynchronous callback(비동기)

console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

function printImmediately(print) {
  print();
}
printImmediately(()=>console.log('hello'));

//출력시 1 3 hello 2

hoisting해서 함수선언을 제일 위에 올려 놓음.
function printImmediately(print) {
  print();
}
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');
printImmediately(()=>console.log('hello'));

 

 

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);

//2초뒤에 console에 async callback이라고 뜸

//hoisiting되면
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(()=> console.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)
    }
    );

가독성이 떨어짐.

유지보수의 어려움.

 

출처 : 드림코딩

 

'javascript' 카테고리의 다른 글

closure  (0) 2022.02.02
Execute context  (0) 2022.02.02
While  (0) 2022.01.25
자료구조 Data Structure  (0) 2022.01.24
lexical grammer/어휘문법  (0) 2022.01.24