카테고리 없음

[JavaScript] 비동기 처리의 시작 콜백 이해하기 (11)

반응형

자바스크립트는 동기적인 아이입니다.

호이스팅이된 이후부터 우리가 작성한 순서에 맞춰서 하나하나 실행됩니다.

hoisting이란 var, function declaration이 자동으로 호이스팅됩니다.

 

1. JavaScript is synchronous

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


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

// Asynchronous callback
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);

setTimeout은 브라우져 API이므로 브라우져에게 전달한다. 그리고 응답을 기다리지 않고 다음으로 넘어갑니다.

그리고 1초 후 '2'가 출력됩니다. 

printImmediately함수와 printWithDelay함수는 아마 맨 위로 호이스팅이 되었을 겁니다.

 

정리: 콜백에도 동기적으로 실행하는 방법이 있고 비동기적으로 실행하는 방법도 있습니다.

 

 

2. Callback hell example

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}`);
      },
      error => {
        console.log(error);
      }
    );
  },
  error => {console.log(error)}
)

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형