Promise
[Promise]
- JS에서 제공하는 비동기를 간편하게 처리할 수 있도록 도와주는 object
- 정상적으로 기능이 실행되면 성공메시지와 처리된 결과값을 전달해주고, 에러나 나면 에러가 발생
(1) State : pending(수행중인상태) --> fullfilled(완료) or rejected(수행실패)
(2) Producer vs Consumer : 제공하는 사람과 쓰는 사람의 차이점을 이해할 필요가 있다.
[Producer]
- promise는 클래스이기 때문에 new를 사용해 생성
- 새로운 promise가 만들어질 때는 excutor가 자동으로 실행된다.
(1) resolve : 기능을 정상적으로 수행해서 마지막에 최종 데이터를 전달
(2) reject : 기능을 수행하다가 문제발생시 호출
'use strict';
// Promise is a JavaScript object for asynchronous operation.
// 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'));
}, 2000);
});
[Consumers : then, catch, finally]
(1) then : 정상적으로 수행되었을 때 / then이 호출 -> promise가 리턴 -> catch 등록 (Chaining)
(2) catch : 문제가 발생했을 때 실행
(3) finally : 성공 실패 상관 없이, 무조건 실행
// 2. Consumers: then, catch, finally
promise //
.then(value => {
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log('finally');
});
[Promise chaining]
// 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)); //5
[Error Handling]
// 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);
[💩 -> 🌟]
// Callback Hell example
class UserStorage {
loginUser(id, password) {
return new Promise((resolve, reject) => { //Promise 리턴
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);
});
}
// Homework Answer 🚀
async getUserWithRole(user, password) {
const id = await this.loginUser(user, password);
const role = await this.getRoles(id);
return role;
}
}
// Original code from Youtube course
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your passrod');
userStorage
.loginUser(id, password)
.then(userStorage.getRoles) //함수 호출
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role`)) //잘받아온다면
.catch(console.log);
// Homework Answer 🚀
userStorage
.getUserWithRole(id, password)
.catch(console.log)
.then(console.log);
Thanks for 드림코딩
'Front-end > Web' 카테고리의 다른 글
[JS] 자바스크립트 함수 기본편 (0) | 2021.08.28 |
---|---|
[JS] async, await, Promise APIs (0) | 2021.08.28 |
[JS] 비동기 처리, callback (0) | 2021.08.28 |
[JS] JSON 개념정리와 활용방법 (0) | 2021.08.27 |
[JS] 10가지 배열함수들, Array APIs 총정리 (0) | 2021.08.27 |
댓글