๋ฐ์ํ
๐ Promise
- ES6
- ์๋ฐ์คํฌ๋ฆฝํธ์์ ์ ๊ณตํ๋ ๋น๋๊ธฐ ์ฝ๋๋ฅผ ๊ฐํธํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋๋ก ๋์์ฃผ๋ object
- ํ๋ก๋ฏธ์ค๋ ์ด๋ค ๊ธฐ๋ฅ์ ์คํํ๊ณ ๋์ ์ ์์ ์ผ๋ก ๋์ํ๋ฉด, ์ฑ๊ณต์ ๋ฉ์ธ์ง์ ํจ๊ป ์ฒ๋ฆฌ๋ ๊ฒฐ๊ณผ๊ฐ์ ์ ๋ฌํด์ค๋ค.
๋ง์ฝ ์์์น ๋ชปํ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ฉด error๋ฅผ ์ ๋ฌํด์ค๋ค. - Producer vs Consumer (์์ฐ์์ ์ฌ์ฉ์ ์ฐจ์ด์ ์ดํด)
- ๋น๋๊ธฐ ์ํ์ํ๋ฅผ ๊ฐ์ง๋ค.
Promise State
pending(๋ณด๋ฅ) -> fulfilled(์ดํ) or rejected(๊ฑฐ๋ถ)
1. Producer (์์ฐ์)
- Promise ๊ฐ์ฒด๊ฐ ์์ฑ๋๋ ์ฆ์ executor(์ฝ๋ฐฑํจ์)๊ฐ ์คํ๋๋ค.
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read file O/I)
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
});
2. Consumer (์๋น์)
- then, catch, finally
promise
.then((value) => {
// promise๊ฐ ์ ์์ ์ผ๋ก ์ํ๋๋ฉด resolve๋ก ์ ๋ฌํ value๊ฐ ๋ค์ด์ด
// then์ ํธ์ถํ๋ฉด ๋ค์ promise๊ฐ ํธ์ถ๋จ.
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
- catch๋ก error๋ฅผ ํจ๋ค๋ง ํ ์ ์๋ค
- error๊ฐ ๋ฐํํด๋ catch๋ฅผ ์ด์ฉํ๋ฉด ์ ์ฒด์ ์ธ Promise ์ฒด์ธ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ง ์๋๋ก ์ฒ๋ฆฌ๋ฅผ ํ ์ ์๋ค.
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) //(hen) => getEgg(hen) ์๋ต๊ฐ๋ฅ
.catch((error) => {
return '๐ฅฏ'; // ๊ณ๋์ ๋ฐ์์ฌ ๋ ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด ๋นต์ผ๋ก ๋์ฒด
})
.then(cook)
.then(console.log)
.catch(console.log);
์ฐธ๊ณ
๐๋๋ฆผ์ฝ๋ฉ ์๋ฆฌ๋์ youtube๊ฐ์๋ฅผ ๋ณด๊ณ ๊ณต๋ถํ ๋ด์ฉ์ ์ ๋ฆฌํ ํฌ์คํ ์ ๋๋ค๐
๐youtube๊ฐ์ https://www.youtube.com/watch?v=JB_yU6Oe2eE&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=12
๋ฐ์ํ
'์ธ์ด > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
TIL01 | JavaScrpit ๋ณ์ (0) | 2021.09.26 |
---|---|
[JS] Dynamic typing (dynamic type vs static type) (0) | 2021.07.10 |
[JS] undefined์ null (0) | 2021.07.10 |
[JS] async function (0) | 2021.07.08 |
[JS] Array api ์ด ์ ๋ฆฌ (0) | 2021.07.05 |