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

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

1,128  

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

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

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

 

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

  }

);

 



분류 제목
GO-터커 GO 35강 - Heap 이용한 문제 풀이
GO-터커 GO 34강 - Heap2
GO-터커 GO 33강 - Heap
GO-터커 GO 32강 - BST (이진트리와 이진검색 트리)
GO-터커 GO 31강 - Tree BFS 와 Dijkstra
GO-터커 GO 30강 - Tree DFS
GO-터커 GO 29강 - Tree
GO-터커 GO 28강 - Packaging 과 Stack, Queue
GO-터커 GO 27강 - Double Linked List
GO-터커 GO 26강 - Linked List
GO-터커 GO 보충 - Instance (인스턴스)
GO-터커 GO 보충 - Slice (슬라이스) 3
GO-터커 GO 25강 - Slice (슬라이드) 2
GO-터커 GO 24강 - Slice (슬라이드) 1
GO-터커 GO 23강 - Garbage Collector (가비지 컬럭터)
GO-터커 GO 22강 - 숫자야구 만들기 2
GO-터커 GO 21강 - 숫자야구 만들기 1 (32:33)
GO-터커 GO 20강 - Pointer (포인터) (42:27)
GO-터커 GO 19강 - 구조체 (31:35) ※ PHP 언어의 CLASS (클래스)와 유사
GO-터커 GO 18강 - 배열, Radix Sort (34:34)
8/35
목록
찾아주셔서 감사합니다. Since 2012