Develop/Javascript
Promise
์คํํ
2021. 2. 24. 21:26
๐ Promise
-
ํ๋ก๋ฏธ์ค๋ JS์์ ์ ๊ณตํ๋ ๋น๋๊ธฐ ์ฝ๋๋ฅผ ๊ฐํธํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋๋ก ๋๋ object.
-
ํ๋ก๋ฏธ์ค๋ ์ด๋ค ๊ธฐ๋ฅ์ ์คํํ๊ณ ๋์ ์ ์๋์์ ์ฑ๊ณต๋ฉ์ธ์ง + ํจ๊ป ์ฒ๋ฆฌ๋ ๊ฒฐ๊ณผ๊ฐ ์ ๋ฌ// ์์์น ๋ชปํ ๋ฌธ์ ๊ฐ ๋ฐ์์ error์ ๋ฌ
-
State: pending(๋ณด๋ฅ) → fulfilled(์ฑ๊ณต์ ์ธ ์๋ฃ) or rejected(๊ฑฐ๋ถ)
-
Promise์ object์ธ Produce vs Consumer
1. Producer (์์ฐ์)
- ํ๋ก๋ฏธ์ค๋ ํด๋์ค์ฌ์ new๋ผ๋ ์์ฑ์๋ก ์์ฑ๊ฐ๋ฅ
- ํ๋ก๋ฏธ์ค๋ executor ๋ ์ฝ๋ฐฑํจ์ ์ ๋ฌํด์ค์ผํ๋ฉฐ ์ด๊ฒ์ ๋๊ฐ์ง ์ฝ๋ฐฑํจ์๋ฅผ(resolve, reject) ๋ค์๋ฐ์
- ํ๋ก๋ฏธ์ค๋ฅผ ๋ง๋๋ ์๊ฐ executor๋ ์ฝ๋ฐฑํจ์ ๋ฐ๋ก ์คํ
const promise = new Promise((resolve, reject)=>{
//doing some heavy work(network, read files)
// => ๋๊ธฐ์ ์ด๋ผ๋ฉด ๊ธฐ๋ค๋ฆฌ๋๋ผ ์๊ฐ ๋๋ฌด ์ฐ๋๊น ๋น๋๊ธฐ์ ์ถ์ฒ
console.log('doing something...');
setTimeout(()=>{
resolve('dada'); // ์ฑ๊ณต์ ์ผ๋ก ๋ง๋ฌด๋ฆฌํ์๋ resolve์ ๊ฐ๊ณต๋ ๋ฐ์ดํฐ ์ ๋ฌํด์ ํธ์ถ
//reject(new Error('no network')); // Error๋ฐ์ํ์๊ฒฝ์ฐ
},2000)
}); // -> ์ฌ์ฉ์๊ฐ ์๊ตฌํ์ ๋ ์คํ๋๋๋ก ๋ง๋ค์ด์ผํ๋ค๋ฉด ๋ค์๊ณผ ๊ฐ์ ์ํ๋ ๋ถํ์ํ ํต์ ์ ์ผ๊ธฐํ ์ ์์
2. Consumer (์๋น์)
- then, catch, finally๋ฅผ ํตํด์ ๊ฐ์ ๋ฐ์ ์ฌ ์ ์์
- promise object ๋ง๋ค๋ ๋น๋๊ธฐ์ ์ผ๋ก ์ํํ๊ณ ์ถ์ ๋ด์ฉ๋ค์ ์์ ์ ์ด์ค ํ ์ฑ๊ณต์ ์ด๋ฉด resolveํธ์ถ ์คํจ๋ฉด reject(์ด์ )ํธ์ถ
- ๊ทธ ํ ์ด ํ๋ก๋ฏธ์ค๋ฅผ ์ด์ฉํด์ then, catch๋ก ์ฑ๊ณต๊ฐ, ์๋ฌ๋ฅผ ๋ฐ์์์ ์ํ๋ ๋ฐฉ์์ผ๋ก ์ฒ๋ฆฌํด์ฃผ๋ฉด ๋๋ค.
promise
.then((value)=>{ //์ด๋ value๋ resolve๊ฐ ์ ๋ฌํ ์ธ์๋ฅผ ๋ฐ๋๋ค.
console.log(value);
})
.catch(error =>{ //์ด๋๋ reject์ ์ ๋ฌํด์ค ์๋ฌ ์ ๋ฌ
console.log(error);
});
.finally(()=>{ //finally๋ ์ฑ๊ณต์คํจ ์ฌ๋ถ ์๊ด์์ด ๋ง์ง๋ง์ ๊ธฐ๋ฅ ์ํ
console.log('finally');
})
// => chaining ์ด์ฉ
3. Promise chaining(์ฐ๊ฒฐํ๊ธฐ)
- then์์ ๊ฐ์ ๋ฐ๋ก ์ ๋ฌ ํ ์ ๋ ์๊ณ , ๋ฆฌํด์ผ๋ก Promise๋ฅผ ์ ๋ฌํด๋ ๋๋ค.
const fetchNumber = new Promise((resolve,reject)=>{
setTimeout(()=> resolve(1),1000);
});
fetchNumber
.then(num => num*2) // 2์ ๋ฌ (1*2)
.then(num => num*3) // 6์ ๋ฌ (2*3)
.then(num => {
return new Promise((resolve,reject)=>{
setTimeout(()=>resolve(num-1),1000); // 5์ ๋ฌ (6-1)
});
})
.then(num => console.log(num)); // ์ถ๋ ฅ์ ์ฝ 2์ด์์ (์์ 1000 ๋ฐ์ 1000)
4. Error handling
- catch ๋ก error๋ฅผ ํจ๋ค๋ง ํ ์ ์๋ค
- error๊ฐ ๋ฐํํด๋ catch๋ฅผ ์ด์ฉํ๋ฉด ์ ์ฒด์ ์ธ Promise ์ฒด์ธ์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ง ์๋๋ก ๋นต๊พธ์ฒ๋ฆฌ๋ฅผ ํ ์ ์๋ค.
const getHen = () =>
new Promise((resolve,reject)=>{
setTimeout(()=> resolve('๐'),2000);
});
const getEgg= hen =>
new Promise((resolve, reject)=>{
setTimeout(()=> resolve(`${hen} => ๐ฅ`),1000);
});
const cook = egg =>
new Promise((resolve, reject)=>{
setTimeout(()=> resolve(`${egg} => ๐ณ`),2000);
})
getHen()
.then(hen => getEgg(hen)) //hen: ๐
.catch(error =>{ //catch๊ฐ ๋ฐ๋ก ์๋ฌ์ฒ๋ฆฌํด์ ์ฒด์ธ์ด ๋นต๊พธ๋์ง ์๊ฒ ๋์ฒดํด์ค
return '๐ฅจ';
})
.then(cook) //! ์ฝ๋ฐฑํจ์ ์ ๋ฌ์ ๋ฐ์์ค๋ ๊ฐ์ผ๋ก ํจ์ ํธ์ถํ๋๊ฒ์ ํ๋ ๋ฃ๋๊ฒฝ์ฐ๋ ์๋ตO
.then(meal => console.log(meal))
.catch(console.log);
then์์ ๋ฐ์์ค๋ value๋ฅผ ๋ฐ๋ก cook์ด๋ผ๋ ํจ์๋ก ์๋ฌต์ ์ ๋ฌ (ํ๋๋ง ๋ฐ๋ก ์ ๋ฌํ ๊ฒฝ์ฐ ์๋ตํด์ ๊ฐ๋จํ ์ฒ๋ฆฌ๋ ๊ฐ๋ฅํจ)