• 회원가입
  • 로그인
  • 구글아이디로 로그인

[JS-엘리] JS 11강 - 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 JavaScript Callback | (JavaScript ES6)

1,186  

동영상 수강 전 본문 내용 스캔.

동영상 수강 후 본문 내용 스캔.

안 보고 직접 코드 타이핑 하기.

 

1. 동기 vs 비동기

 

'use strict';


// Javascript is syncronous.

// Execute the code block in order after hoisting.

// hoisting : var, function declaration


// synchronous (1 → 2 → 3)

console.log('1');

console.log('2');

console.log('3');


// asynchronous (1 → 3 → 2)

console.log('1');

/*

setTimeout(function () { // 브라우저에게 1초후 콜백함수 호출 맡기고, 먼저 3 출력.

  console.log('2');

}, 1000);

*/

setTimeout(() => console.log('2'), 1000); // 화살표함수 사용해 더 간단히 표현.

console.log('3');


// Synchronous callback (1 → 3 → hello → 2)

// 함수 선언은 hoisting 되므로, 'use strict' 코드 바로 밑으로 올린 상태로 인식.

function printImmediately(print) {

  print();

}

printImmediately(() => console.log('hello'));


// Asynchronous callback (1 → 3 → hello → 2 → async callback)

// 함수 선언은 hoisting 되므로, 위 함수 선언 밑으로 올린 상태로 인식.

function printWithDelay(print, timeout) {

  setTimeout(print, timeout);

}

printWithDelay(() => console.log('async callback'), 2000);

 

 

PS. 위 코드는 실제로는 아래처럼 작동.

 

'use strict';


function printImmediately(print) {

    print();

}

function printWithDelay(print, timeout) {

    setTimeout(print, timeout);

}


// Javascript is syncronous.

// Execute the code block in order after hoisting.

// hoisting : var, function declaration


// synchronous (1 → 2 → 3)

console.log('1');

console.log('2');

console.log('3');


// asynchronous (1 → 3 → hello → 2 → async callback)

console.log('1');

setTimeout(() => console.log('2'), 1000); // 화살표함수 사용해 더 간단히 표현.

console.log('3');

printImmediately(() => console.log('hello'));

printWithDelay(() => console.log('async callback'), 2000);

 

 

 

2. 콜백 지옥

 

// 콜백 지옥 : 콜백함수를 안긴 형태로 중첩적으로 호출하는 형태로 짠 코드

// 문제점: 유지보수 어려움 (∵ 1. 가독성 저하 2. 디버깅 곤란.)

// Callback Hell example

class UserStorage {

  loginUser(id, passwod, 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) => {

        // userWidthRole는 { name: 'ellie', role: 'admin' } 객체 가리키는 임의의 매개변수임.

        alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`);

        // 결과값 : Hello ellie, you have a admin role

        // alert(`Hello ${user.name}, you have a ${user.role} role`);

        // 결과값 : Hello undefined, you have a undefined role

      },

      (error) => {

        console.log(error);

      }

    );

  },

  (error) => {

    console.log(error);

  }

);

 



분류 제목
JS-생코 JS 46강 - UI,API 그리고 문서 (1/2) : 수업소개
JS-생코 JS 45강 - 모듈 (5/5) : 라이브러리의 사용
JS-생코 JS 44강 - 모듈 (4/5) : 라이브러리란?
JS-생코 JS 43강 - 모듈 (3/5) : Node.js의 모듈화
JS-생코 JS 42강 - 모듈 (2/5) : 모듈화
JS-생코 JS 41강 - 모듈 (1/5) : 모듈이란?
JS-생코 JS 40강 - 객체 (3/3) : 객체지향 프로그래밍
JS-생코 JS 39강 - 객체 (2/3) : 객체와 반복문의 조우
JS-생코 JS 38강 - 객체 (1/3) : 객체의 문법
JS-생코 JS 37강 - 배열 (5/5) : 제거와 정렬
JS-생코 JS 36강 - 배열 (4/5) : 데이터의 추가
JS-생코 JS 35강 - 배열 (3/5) : 배열과 반복문의 조우
JS-생코 JS 34강 - 배열 (2/5) : 배열의 효용
JS-생코 JS 33강 - 배열 (1/5) : 배열의 문법
JS-생코 JS 32강 - 함수 (5/5) : 다양한 정의 방법
JS-생코 JS 31강 - 함수 (4/5) : 출력
JS-생코 JS 30강 - 함수 (3/5) : 입력
JS-생코 JS 29강 - 함수 (2/5) : 함수의 효용
JS-생코 JS 28강 - 함수 (1/5) : 함수란?
JS-생코 JS 27강 - 반복 (6/6) : 반복문의 중첩 (= 이중 반복문) ★★★★★
25/35
목록
찾아주셔서 감사합니다. Since 2012