본문 바로가기
JavaScript/드림코딩 엘리 - 자바스크립트 기초 강의 (ES5+)

드림코딩 엘리 - 자바스크립트 기초 강의(ES5+) (12편)

by 정ㅇr 2021. 11. 18.
728x90

Promise

- 자바스크립트에서 제공하는 비동기를 간편하게 처리할 수 있게 하는 Object

- 정해진 기능을 성공적으로 처리하면 메세지와 함께 결과값을 반환, 처리하지 못하면 에러를 전달해줌

- 콜백함수 대신에 유용하게 쓰일 수 있음

 

파일을 읽어오거나, 네트워크 요청 하는 것들은 시간이 걸리는 작업이기 때문에 비동기로 처리하는 것이 좋음

만약, 동기적으로 처리하게 된다면 작업을 하는 동안 다음 코드가 실행되지 않는 번거로움이 발생하기 때문이다.


Promise는 만드는 순간에 excuter 함수를 실행하기 때문에, 원하지 않을 때도 네트워크 통신이 일어날 수 있음을 유의해야 한다.

'use strict';

// Promise is a JavaScript object for asynchoronous operation.
// State: pending -> fulfuilled 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. Consumers: then, catch, finally
// promise가 잘 실행이 되어서 resolve에 담긴 값이 value로 들어오게 됨
promise // then을 사용하면 promise가 리턴되기 때문에 다시 catch를 사용할 수 있음 (chaining)
    .then((value) => {
        console.log(value);
    })
    .catch(error => {
        console.log(error);
    })
    .finally(() => { // 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(() => reject(new Error(`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);

콜백 함수로 작성한 내용 Promise로 바꾸기

// 콜백 지옥 -> 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 => alert(`Hello ${user.name}, you have a ${user.role} role`))
    .catch(console.log);

 

출처

https://www.youtube.com/watch?v=JB_yU6Oe2eE&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=13&ab_channel=%EB%93%9C%EB%A6%BC%EC%BD%94%EB%94%A9by%EC%97%98%EB%A6%AC

반응형

댓글