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

[JS-엘리] JS 12강 - Promise 개념부터 활용까지 JavaScript Promise | (JavaScript ES6) ※ 프라미스/프로미스

846  

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

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

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

 

promise.js

 

'use strict';


// Promise is a JavaScrit object for asynchronous operation.

// State: pendding → fulfilled or rejected

// Producer vs. Consumer


// 1. Producer

// When new Promise is created, the executor runs automatically.

const promise = new Promise((resolve, reject) => {

  // doing some heavy work (network, read files)

  console.log('doing something...');

  setTimeout(() => {

    resolve('ellie');

    // reject(new Error('no network'));

  }, 2000);

});


// 2. Consumer: then, catch, finally

// 주의: then, catch, finally는 한 구문이라, 끝에만 ; (세미콜론) 붙임.

promise

  .then((value) => {

    // 성공 시 실행

    console.log(value);

  })

  .catch((error) => {

    // 실패 시 실행

    console.log(error);

  })

  .finally(() => {

    // 성공・실패 시 실행

    console.log('finally');

  });


// 3. Promise chaining

const fetchNumber = new Promise((resolve, reject) => {

  setTimeout(() => resolve(1), 1000);

});


fetchNumber

  .then((num) => num * 2) // 1 => 1*2 = 2

  .then((num) => num * 3) // 2 => 2*3 = 6

  .then((num) => {

    return new Promise((resolve, reject) => {

      setTimeout(() => resolve(num - 1), 1000); // 6 - 1 = 5

    });

  })

  .then((num) => console.log(num)); // 5 => 5

// then은 value를 전달할 수도 있고, Promise 자체를 전달할 수도 있음.

// 총 2초 소요.

// 결과값: 5

// 비동기 코드들을 묶어서 (= chaining) 표현 가능.


// Promise를 chaining했을 때 Error 다루는 법 소개.

// 4. Error Handling

const getHen = () =>

  new Promise((resolve, reject) => {

    setTimeout(() => resolve('닭'), 1000);

  });

const getEgg = (hen) =>

  new Promise((resolve, reject) => {

    setTimeout(() => resolve(`${hen} => 달걀`), 1000); // 성공 시

    // setTimeout(() => reject(new Error(`error! ${hen} => 달걀`)), 1000); // 실패 시

  });

const cook = (egg) =>

  new Promise((resolve, reject) => {

    setTimeout(() => resolve(`${egg} => 후라이`), 1000);

  });


// ******************************************

// const getEgg 부분에서 성공 코드 사용 가정 시

// ******************************************

/*

getHen() // 닭

  .then((hen) => getEgg(hen)) // 닭 => 달걀

  .then((egg) => cook(egg)) // 닭 => 달걀 => 후라이

  .then((meal) => console.log(meal)); // 출력: 닭 => 달걀 => 후라이


// 받아온 value 하나를 그대로 다른 함수의 독립변수로 사용 시 아래처럼 표현 가능.

getHen() // 닭

  .then(getEgg) // 닭 => 달걀

  .then(cook) // 닭 => 달걀 => 후라이

  .then(console.log); // 출력: 닭 => 달걀 => 후라이


// 위 축약된 코드를 아래처럼 한 줄로 표현 가능.

getHen().then(getEgg).then(cook).then(console.log); // 출력: 닭 => 달걀 => 후라이

*/


// 위처럼 한 줄로 하면 가독성 떨어지므로, 아래처럼 // 붙이고 Enter키 누르면 자동 줄바꿈 됨.

getHen() //

  .then(getEgg)

  .then(cook)

  .then(console.log); // 성공 시 출력: 닭 => 달걀 => 후라이


// ******************************************

// const getEgg 부분에서 실패 코드 사용 가정 시

// ******************************************


// 에러 대비 코드 사용 X

getHen() //

  .then(getEgg)

  .then(cook)

  .then(console.log)

  .catch(console.log); // 출력: Error: error! 닭 => 달걀


// 에러 대비 코드 사용 O

getHen() //

  .then(getEgg)

  .catch((error) => {

    // 실패 시 대체 코드

    return '빵';

  })

  .then(cook)

  .then(console.log)

  .catch(console.log); // 출력: 빵 => 후라이


 

 

callback-to-promise.js

 

'use strict';


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

  }

);

*/


// Callback Hell Escape by using Promise

class UserStorage {

  loginUser(id, password) {

    return new Promise((resolve, reject) => {

      setTimeout(() => {

        if (

          (id === 'ellie' && password === 'dream') ||

          (id === 'coder' && password === 'academy')

        ) {

          resolve(id);

        } else {

          reject(new Error('not found'));

        }

      }, 2000);

    });

  }


  getRoles(user) {

    return new Promise((resolve, reject) => {

      setTimeout(() => {

        if (user === 'ellie') {

          resolve({ name: 'ellie', role: 'admin' });

        } else {

          reject(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)

  .then(userStorage.getRoles) // 의미: .then(user => userStorage.getRoles(user))

  .then((user) => alert(`Hello ${user.name}, you have a ${user.role} role.`))

  .catch(console.log);

 



분류 제목
PHP-쩡원 PHP 기초 9강 - 게시판 만들기 (파일수정, 파일삭제, 스마트에디터달기)
JS-서기 JS 14강 - HTML CSS JS 혼용하기 (=getElementsBy 시리즈 = JS선택자) ★★★★★
regex PHP 정규표현식 패턴 8강 - [ - ] (대괄호 안 하이픈) ─ 매치되는 문자의 후보 범위
JS-엘리 JS 10강 - JSON 개념 정리 와 활용방법 | (JavaScript ES6)
PHP7-서기 PHP7 33강 - 부트스트랩을 이용한 웹사이트 만들기
PHP-생코 PHP 69강 - 데이터베이스 데이터의 추가, 조회, 수정, 삭제 (INSERT, SELECT, UPDATE…
PHP-쩡원 PHP 기초 4강 - 회원가입 만들기 (폼입력값 유효성검사) (Form Validation)
PHP-쩡원 PHP 중급 2강 - 쇼핑몰 (회원가입, 로그인, 로그아웃. 기타) 페이지
JS-서기 JS 7강 - 모든 구구단 (= 중첩포문 = 이중포문 = 이단포문) (for double loop)
JS-서기 JS 5강 - for반복문 흐름, 1~100 출력 및 합산 3
PHP-서기 php 40. 첨부파일 업로드 ★★★
PHP-쩡원 PHP 기초 1강 - APMSETUP 설치 + PhpMyAdmin 설치
PHP-쩡원 PHP 중급 1강 - 쇼핑몰 (Root 디렉터리 , index파일, mysql파일 + 회원가입 페이지) 만…
JS-엘리 JS 13강 - 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise API…
JS-바위 JS 52~55강 - 멀티플 슬라이드 (Multiple Slideshow)
C-나동빈 C 언어 7강 - 조건문 & 반복문 ② - 사각형 , 피라미드 만들기 (14분 58초)
PHP-생코 PHP 55강 - 이미지 예제2 (워터마크 watermark) ★★★
regex PHP 정규표현식 패턴 12강 - 수량자 ─ * (별표) : 기호 앞 문자가 적어도 0개 이상
PHP7-서기 PHP7 26강 - fabric.js (캔버스 라이브러리) 사용 방법
JS-바위 JS 17강 - 탭스 (tabs) 메뉴 + 무빙탭메뉴 (Moving Tab Menu) = 움직이는 탭메뉴
3/35
목록
찾아주셔서 감사합니다. Since 2012