Script

Callback 본문

Javascript

Callback

scripter. 2022. 6. 17. 19:26

1.동기와 비동기

자바스크립트는 동기적이다
hoisting 후 코드 블록을 순서대로 실행한다
hoisting: var 변수와, 함수 선언들이 자동적으로 맨위로 올라가는 것을 말한다.

 

동기

정해진 순서에 맞게 코드가 실행되는것

console.log('1');
console.log('2');
console.log('3');

 

비동기

언제 코드가 실행될지 예측할수 없는것

console.log('1');
setTimeout(()=>{
  console.log('2');
},1000);//콜백함수
console.log('3');//1 3출력 후 1000ms뒤에 2출력

 

2.동기적 콜백과 비동기적 콜백

 

콜백함수란?

 

  • 다른 함수의 인자로써 이용되는 함수
  • 어떤 이벤트에 의해 호출되어지는 함수

 

동기적 콜백

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

 

비동기적 콜백

function printWithDelay(print, timeout){
  setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'),2000);
//2초 뒤에 async callback 출력

 

3.콜백 지옥 

로그인 기능을 만든다고 가정

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

//콜백체인의 문제점
//1.가독성이 떨어진다.
//2.따라서 디버깅,유지보수할때 난항을 겪게된다.

'Javascript' 카테고리의 다른 글

async & await  (0) 2022.06.18
Promise  (0) 2022.06.18
JSON  (0) 2022.06.17
배열 api  (0) 2022.06.17
배열  (0) 2022.06.15
Comments