๐ Point
๐ promise?
๐ promise state
๐ consumer: then, catch, finally
Promise๋ฅผ ๊ณต๋ถํ๋ฉฐ ์ด์ ์ ๋ฌ์ผ ํ ๋ด์ฉ
promise๋ฅผ ๋ง๋๋ ๊ตฌ์กฐ๋ ๊ฐ๋จํ๊ฒ ์๋์ฒ๋ผ ํํํ ์ ์์ต๋๋ค.
const promise = new Promise(resolve, reject) => {});
const promise = new Promise(resolve, reject) => {
setTimeout(() => {
resolve('hyojin'); --case A
reject(new Error('no network'));-- case B
}, 2000);
});
์ฃผ์
โญ๏ธ pormise๋ฅผ ๋ง๋๋ ์๊ฐ ๋ฐ๋ก ๋คํธ์ํฌ ํต์ ์ ์ํํ๊ฒ ๋๋ค.
โญ๏ธ ๋ฐ๋ผ์ ์ฌ์ฉ์๊ฐ ์๊ตฌํ ๋๋ง(ex_๋ฒํผ์ ๋๋ฅผ ๋) ์คํํ๊ณ ์ถ๋ค๋ฉด, ์ด ์ ์ ์ผ๋ํด์ผํ๋ค.
Promise
.then(value => {
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log('finally');
});
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('๐'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${hen} => ๐ฅ`), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => ๐ณ`), 1000);
});
getHen()
.then(hen => getEgg(hen))
.then(egg => cook(egg))
.then(meal => console.log(meal));
---------------------------------------------
// ๐ => ๐ฅ => ๐ณ
---------------------------------------------
// ๋ฐ์์ค๋ ๊ฒ์ด ํ๋๋ฉด ์๋์ฒ๋ผ ๊ฐ๋จํ๊ฒ ํํํ ์ ์๋ค
getHen()
.then(getEgg)
.then(cook)
.then(console.log);
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('๐'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(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);
----------------------
//๐ฅ => ๐ณ (์๋ฌ ๋นต๊พธ ์ฒ๋ฆฌ!)
// ๋ง์ฝ ๋นต๊พธ์ฒ๋ฆฌ๋ฅผ ํ์ง ์์๋ค๋ฉด?
// Error: error! ๐ => ๐ฅ