๐ŸŸจ JavaScript/๊ฐœ๋…

[๋“œ๋ฆผ์ฝ”๋”ฉ] ์ฝœ๋ฐฑํ•จ์ˆ˜ (2) : ์ฝœ๋ฐฑ์ง€์˜ฅ ํƒˆ์ถœ, Promise (State, Producing)

Zoeeey 2022. 7. 22. 15:16

Promise

Promise๋Š” javascript์— ๋‚ด์žฅ๋˜์–ด์žˆ๋Š” object๋กœ, ์ด๋ฅผ ํ†ตํ•ด์„œ ๋น„๋™๊ธฐ ์ฝ”๋“œ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ๋„คํŠธ์›Œํฌํ†ต์‹ ์„ ํ•œ๋‹ค๋˜์ง€, ํŒŒ์ผ์„ ์ฝ์–ด์˜จ๋‹ค๋˜์ง€ ํ•˜๋Š” ๋“ฑ์˜ ๋ฌด๊ฑฐ์šด ์ž‘์—…์„ ํ•  ๋•Œ๋Š” ์˜ค๋ž˜ ๊ฑธ๋ฆฌ๋ฏ€๋กœ Promise๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค. ๋ฌด๊ฑฐ์šด ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•˜๋ฏ€๋กœ ์‚ฌ์šฉ์ž๊ฐ€ ์š”์ฒญํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ๋„ ์ผ์–ด๋‚˜๋Š” ๋ถˆํ•„์š”ํ•œ ๋„คํŠธ์›Œํฌํ†ต์‹ (promiseํ•จ์ˆ˜์˜ ์‹คํ–‰)์„ ๋ฐฉ์ง€ํ•ด์•ผ ํ•œ๋‹ค.
  • new Promise๊ฐ€ ๋งŒ๋“ค์–ด์ง€๋Š” ์ˆœ๊ฐ„, ํ•ด๋‹น executor ํ•จ์ˆ˜๊ฐ€ ์ž๋™์œผ๋กœ ์‹คํ–‰๋˜๋ฏ€๋กœ ์ฃผ์˜ํ•˜์ž.

promise๋Š” ์•„๋ž˜ ๋‘ ๊ฐ€์ง€๋ฅผ ์—ผ๋‘์— ๋‘๋ฉด ์ข‹๋‹ค.


1. State(์ƒํƒœ)

process๊ฐ€ ๋ฌด๊ฑฐ์šด operation์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ๋Š”์ง€/์™„๋ฃŒ๋˜์—ˆ๋‹ค๋ฉด ์„ฑ๊ณตํ–ˆ๋Š”์ง€/์‹คํŒจํ–ˆ๋Š”์ง€์˜ ์ƒํƒœ

  • pending : operation์„ ์ˆ˜ํ–‰ ์ค‘์ธ ์ƒํƒœ
  • fulfilled : operation์„ ์„ฑ๊ณต์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•œ ์ƒํƒœ
  • rejected : ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๊ฑฐ๋‚˜, ๋„คํŠธ์›Œํฌ์— ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธด ๋“ฑ ์‹คํŒจํ•œ ์ƒํƒœ

2. Producing

Producer(๋ฐ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•˜๋Š” ์‚ฌ๋žŒ)์™€ Consumer(๋ฐ์ดํ„ฐ๋ฅผ ์†Œ๋น„ ํ•˜๋Š” ์‚ฌ๋žŒ)์˜ ์ฐจ์ด

Producer

- resolve

const promise = new Promise((resolve, reject) => {
  //doing some heavy work (network, read files)
  console.log('doing something...');
  setTimeout(() => {
    resolve('Noran');
  }, 2000);
})

- reject

const promise = new Promise((resolve, reject) => {
  //doing some heavy work (network, read files)
  console.log('doing something...');
  setTimeout(() => {
    reject(new Error('no network'));
  }, 2000);
})

Consumer

- then

// ์ •์ƒ์ ์œผ๋กœ ์ˆ˜ํ–‰์ด ๋œ๋‹ค๋ฉด
promise.then((value) => { //value๋Š” ์œ„์˜ promiseํ•จ์ˆ˜์—์„œ resolve๋œ data
  console.log(value);
})

//"Noran"

- catch ์ถ”๊ฐ€

// ์ •์ƒ์ ์œผ๋กœ ์ˆ˜ํ–‰์ด ๋œ๋‹ค๋ฉด
promise
  .then(value => { //value๋Š” ์œ„์˜ promiseํ•จ์ˆ˜์—์„œ resolve๋œ data
  console.log(value);
}) //then์€ ๋˜‘๊ฐ™์€ promise๋ฅผ returnํ•œ๋‹ค.
// reject๋˜์–ด error๊ฐ€ ์ผ์–ด๋‚œ๋‹ค๋ฉด
  .catch(error => { //error๋ฅผ uncaught๊ฐ€ ์•„๋‹Œ ์›ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋œฐ ์ˆ˜ ์žˆ๊ฒŒ
  console.log(error);
});

//Error: no network

- finally ์ถ”๊ฐ€

// ์ •์ƒ์ ์œผ๋กœ ์ˆ˜ํ–‰์ด ๋œ๋‹ค๋ฉด
promise
  .then(value => { //value๋Š” ์œ„์˜ promiseํ•จ์ˆ˜์—์„œ resolve๋œ data
  console.log(value);
}) //then์€ ๋˜‘๊ฐ™์€ promise๋ฅผ returnํ•œ๋‹ค.
// error๊ฐ€ ๋œฌ๋‹ค๋ฉด
  .catch(error => { //error๋ฅผ uncaught๊ฐ€ ์•„๋‹Œ ์›ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋œฐ ์ˆ˜ ์žˆ๊ฒŒ
  console.log(error);
})
// ๊ฒฐ๊ณผ๊ฐ€ ์–ด๋–ป๋“  ๋งˆ์ง€๋ง‰์— ์‹คํ–‰๋œ๋‹ค
.finally(() => {
  console.log('์–ด์จŒ๋“  ์‹คํ–‰๋จ');
});

//Error: no network
//'์–ด์ฉ„๋“  ์‹คํ–‰๋จ'

์ถœ์ฒ˜ : ๋“œ๋ฆผ์ฝ”๋”ฉ https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko/