본문 바로가기
Front-end/Web

[JS] 비동기 처리, callback

by 안녕주 2021. 8. 28.

Callback

[동기와 비동기]

(1) 동기적 Synchronous

- javascript는 동기적이다.

- hoisting이 된 이후부터 코드가 우리가 작성된 순서대로 동기적으로 실행

- hoisting : var 변수나 함수선언들이 제일 위로 올라가는 것

(2) 비동기적 Asynchronous :  언제 코드가 실행될지 예측할 수 없다.

'use strict';

// JavaScript is synchronous.
// Execute the code block in order after hoisting.
// hoisting: var, function declaration
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

 

[콜백 마지막 정리]

- Callback : 나중에 다시 불러죠!

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

 

[콜백 지옥 체험]

// 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 passrod');
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) 비지니스 로직을 파악하기 힘들다

(3) 디버깅, 유지보수가 어렵다

 


Thanks for 드림코딩

https://youtu.be/s1vpVCrT8f4

댓글