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

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

1,561  

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

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

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

 

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-서기 JQ 4강 - 허버메뉴
JS-서기 JQ 3강 - 이벤트, 이펙트 (=메서드)
JS-서기 JQ 2강 - JQUERY (제이쿼리) 다운로드, 외부링크, 기본구문
JS-서기 JQ 1강 - JQUERY (제이쿼리) 개념, CSS 선택자
JS-서기 JS 17강 - 허버메뉴만들기
JS-서기 JS 16강 - this객체, 조건분기, 속성설정
JS-서기 JS 15강 - CSS 선택자
JS-서기 JS 14강 - HTML CSS JS 혼용하기 (=getElementsBy 시리즈 = JS선택자) ★★★★★
JS-서기 JS 13강 - DOM (돔: Document Object Model 문서객체모델)
JS-서기 JS 12강 - 이벤트핸들러2 (event handler) - onload, onunload, / confi…
JS-서기 JS 11강 - 이벤트핸들러1 (event handler)
JS-서기 JS 10강 - 사용자정의함수 (조건, 경고창, 페이지이동) (function, if, alert, url,…
JS-서기 JS 9강 - 함수 제작 (= 사용자정의함수)
JS-서기 JS 8강 - for문 안쪽에 if문 사용 (= 행렬 표만들기 = 줄바꿈 = 줄바꾸기 = 줄변경 = 라인변…
JS-서기 JS 7강 - 모든 구구단 (= 중첩포문 = 이중포문 = 이단포문) (for double loop)
JS-서기 JS 6강 - 특정 구구단
JS-서기 JS 5강 - for반복문 흐름, 1~100 출력 및 합산 3
JS-서기 JS 4강 - else if 조건문, && 기호 의미
JS-서기 JS 3강 - 변수선언, prompt() 입력함수, if조건문, 사이트 이동 ★
JS-서기 JS 2강 - 변수 선언 및 출력
11/35
목록
찾아주셔서 감사합니다. Since 2012