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

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

816  

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

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

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

 

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

 



분류 제목
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