프로미스 개념부터 활용까지 JavaScript Promise

굥굥이·2022년 3월 15일
0

💖 Promise란?

Promise는 비동기를 간편하게 처리할 수 있도록 도와주는 object다. 정상적으로 기능이 수행되었다면 성공의 메세지와 함께 처리된 결과값을 전달하고, 문제가 발생했다면 에러를 전달한다.
그러므로 결국 state는 pending(수행중), fulfilled(성공적으로 완료), rejected(실패) 총 3가지가 있다.

💖 producer 와 consumer

  1. producer
    새로운 promise가 만들어 질 때, excutor함수는 바로 실행되는 점 알고 있어야 한다. ( = 사용자가 요구하지 않아도 바로 실행됨)
    resolve는 값이 정상적으로 수행될 때고, reject는 값이 정상적으로 수행되지 않았을 때이므로 new Error 값을 전달한다.
    네트워크나 파일을 읽는 거와 같이 시간이 걸리는 것들을 비동기로 처리하는 것이 좋다.
const promise = new Promise((resolve, reject) => {
    console.log('doing something...'); //console창에 바로 나오는 걸 보니, promise가 만들어지는 순간 바로 실행됨.(= 사용자가 요구하지도 않았는데 실행)
    setTimeout(()=>{
        resolve('ellie');
        //reject(new Error('no network'));
    },2000);
})
  1. consumer
    then, catch, finally 가 있는데, 값이 정상적으로 수행될 경우(resolve)엔 then, 값이 정상적으로 수행되지 않았을 경우(reject)엔 catch, 어떤 상황이든 하고 싶을 땐 finally를 이용하면 된다(파라미터 필요 없음). catch를 하면 개발자창에서 빨간색에러로 뜨지 않는다. 에러잡기다!
promise
    .then(value => { 
        console.log(value); //ellie라는 값이 들어옴
    })
    .catch(error => {
        console.log(error);
    })
    .finally(() => {
        console.log('finally');
    })

💖 Promise chaining

아직 잘 이해를 못했는데 아마 then, then, then,... 과 같이 과정의 연속을 Promise chaining이라고 하는 거 같다.

const fetchNumber = new Promise((resolve, reject) => {
    setTimeout(()=>resolve(1),1000);
})
fetchNumber
    .then(num => num * 2) //2
    .then(num => num * 3) //6
    .then(num => {
        return new Promise((resolve, reject) => {
            setTimeout(()=> resolve(num-1), 1000); //5
        })
    })
    .then(num => console.log(num));

💖 Error Handling

닭을 받아서 계란을 만들고 계란을 받아서 계란후라이를 만들어보자! getEgg에서 에러가 발생했을 시, 프레즐을 리턴하도록 하여 Error handling도 해보자!
그리고 consumer에서 만약 파라미터값을 하나만 받아서 바로 전달할 땐 파라미터 생략이 가능하다.

const getHen = () => 
    new Promise((resolve, reject) => {
        setTimeout(() => resolve('🐔'), 1000);
    });
const getEgg = hen => 
    new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error(`error! ${hen} => 🥚`), 1000));
    });
const cook = egg => 
    new Promise((resolve, reject) => {
        setTimeout(resolve(`${egg} => 🍳`),1000)
    });
getHen()
    .then(hen => getEgg(hen))
    .catch(error => {
        return '🥨';
    })
    .then(egg => cook(egg))
    .then(meal => console.log(meal)) 
    .catch(() => console.log()); 
   	//then(getEgg).then(cook).then(console.log) 이런 식으로 생략가능!! 

💛 callback 지옥에서 했던 것들을 promise로 해보자!

성공하면 resolve, 실패하면 reject로 값을 넘길 것이므로 callback함수들(onSuccess, onError)은 필요없다.

class UserStorage{ //onSuccess(성공콜백) onError(에러콜백)
    loginUser(id, password){
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                if(
                    (id==='7lo9ve3' && password==='1234') ||
                    (id==='inkyung' && password==='5678')
                    ){
                        resolve(id);
                    }else{
                        reject(new Error('not found'));
                    }
            },2000)
        });
    }
    getRoles(user){
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
                if(user==='7lo9ve3'){
                    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(user => userStorage.getRoles(user))
    .then(user =>  alert(`hello ${user.name}, you have a ${user.role} role`))
    .catch(console.log);
profile
아자아자 파이띵굥!

0개의 댓글