코딩동강

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

1,075

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

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

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

 

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 80~82강 - 자바스크립트 객체 클래스
JS-바위 JS 77~79강 - 자바스크립트 모듈 활용 (Javascript Module)
JS-바위 JS 73~76강 - 테이블 페이지네이션 (Table Pagination)
JS-바위 JS 72강 - AOS 라이브러리 - 슝슝 나타나는 스크롤 애니메이션
JS-바위 JS 69~71강 - 숫자 그래프 애니메이션 (Number Animation)
JS-바위 JS 68강 - animate.css 라이브러리 - 스크롤이벤트 적용
JS-바위 JS 64~67강 - tailwindcss (node js - CSS framework) - CSS 없이 스…
JS-바위 JS 61~63강 - 최신 JS 문법 (ECMA SCRIPT 6) - 변수선언 키워드 let, const, …
JS-바위 JS 60강 - 인스타그램 (instagram) API - 인스타그램 피드를 웹사이트에 출력
JS-바위 JS 56~59강 - 쿠키 (Cookie) 이용해 「오늘 하루 안보기 팝업창 띄우기」 생성
JS-바위 JS 52~55강 - 멀티플 슬라이드 (Multiple Slideshow)
JS-바위 JS 51강 - 스크롤트리거 (scrollTrigger) - 스크롤 애니메이션 구현
JS-바위 JS 46~50강 - 필터링 반응형 갤러리 (Fitered Gallery)
JS-바위 JS 45강 - 하이라이트 무빙 탭 애니메이션 (Highlight Moving Tab animation)
JS-바위 JS 42~44강 - 풀스크린 슬라이드 (FullScreen Slide) 1 - CSS로만 구현
1/47
목록
 홈  PC버전 로그인 일본어
웹디자인언어
서버관리언어
고급코딩언어
그누보드
제작의뢰
Q&A
커뮤니티
웹유틸
회원센터
홈짱 PC버전 로그인