코딩동강

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

795

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

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

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

 

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

 



분류 제목
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버전 로그인 일본어
웹디자인언어
서버관리언어
고급코딩언어
그누보드
제작의뢰 1
Q&A
커뮤니티 4
웹유틸
회원센터
홈짱 PC버전 로그인