rhanziy

javascript. Promise 본문

Html_css_js

javascript. Promise

rhanziy 2022. 1. 28. 19:52
  • Promise는 세 개중 하나의 상태를 갖는다.
    • pending(대기): Promise가 생성되어 작업을 진행 중인 상태
    • fulfilled(이행): Promise가 작업을 성공적으로 완료한 상태
    • rejected(거절됨): Promise가 작업을 완료하였지만 실패한 상태
    • 완료 상태인 fulfilled와 rejected를 합쳐 settled라고도 한다고 함.
    • 이러한 상태 정보는 [[PromiseState]]에 명시된다.
// 비동기를 간편하게 처리할 수 있도록 도와주는 object
// promise is a JavaScript object for asynchronous operation.
// state: pending -> fulfilled or rejected
// Producer vs Consumer

'use strict';

// 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('rani');
    //reject(new Error('no network'));
   }, 2000);
});


// 2. Consumers: 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)
.then(num => num * 3)
.then(num => {
    return new Promise((resolve, reject)=>{
      setTimeout(()=>resolve(num-1), 1000);
    });
}).then(num => console.log(num));

// 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(`${hen} => 🥚`)), 1000);
  });
const cook = egg =>
  new Promise((resolve, reject)=> {
    setTimeout(() => resolve(`${egg} => 🍳`),1000);
  });

  getHen()//
  .then(getEgg)
  .catch(error => {
    return '🍞';
  })
  .then(cook)
  .then(console.log)
  .catch(console.log);
class UserStorage {
  loginUser(id, password){
    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        if (
          (id === 'rani' && 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 === 'rani'){
          resolve({name:'rani', 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 => alert(`Hello ${user.name}, you have a ${user.role} role!`))
.catch(console.log);




// userStorage.loginUser( 콜백함수를 쓰면 이러케. 지저분
//   id, 
//   password, 
//   user =>{
//     userStorage.getRoles(
//       user,
//       userWithRole => {
//         alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role!`);
//       },
//       error => {
//         console.log(error);
//       }
//     );
//   },
//   error=>{
//     console.log(error);
//   }
// );

'Html_css_js' 카테고리의 다른 글

javascript. class와 callback함수  (0) 2022.01.31
javascript. Promise API  (0) 2022.01.29
javascript. Array배열2(filter, map, reduce, ...)  (0) 2022.01.23
javascript. Array배열1  (0) 2022.01.21
javascript. Object객체  (0) 2022.01.21
Comments