티스토리 뷰

javascript

[javascript] promise

tonirr 2020. 11. 19. 00:01
'use strict';
// Promise는 비동기 실행상황을 위한 javascript Object임
//  State: pending -> 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 kkk'));
    }, 2000);
});

// 2. Consumers: then, catch, finally
// value: 함수 실행 후 resolve가 return 한 값
promise.then((value) => {
        console.log(value);
    })
// error: 함수 실행 후 에러 발생시 reject의 return 값을 도출해줌
    .catch(error => {
        console.log(error);
    })
// resolve와 reject에 관계없이 실행되는 코드
    .finally(() => {
        console.log('finally');
    });


// 3. Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 1000);
});

fetchNumber
// 여기에서 num은 resolve에 파라미터로 전달된 값을 의미
.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('hen'), 1000);
    });
const getEgg = hen => 
    new Promise((resolve, reject) => {
        //setTimeout(() => resolve(`${hen} => egg`), 1000);
        setTimeout(() => reject(new Error(`error! ${hen} => egg`), 1000));
    });
const cook = egg => 
    new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${egg} => fri`), 1000);
    });

// getHen()
//     .then(hen => getEgg(hen))
//     .then(egg => cook(egg))
//     .then(meal => console.log(meal));

getHen()
    .then(getEgg)
    .catch(error => {
        return 'bread';
    })
    .then(cook)
    .then(console.log)
    .catch(console.log)
'use-strict';

// Callback Hell example
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) => {
            console.log(`user: ${user}`);
            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);

'javascript' 카테고리의 다른 글

[javascript] Cannot read property 'search' of undefined에러  (0) 2020.12.24
[javascript] - async, await, Promise API  (0) 2020.11.21
[javascript] callback function  (0) 2020.11.18
[javascript] json  (0) 2020.11.17
[Javascript] Array  (0) 2020.11.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함