javascript์˜ ์•ฝ์†(๐Ÿ”–)

3340 ๋‹จ์–ด beginnerstutorialjavascriptwebdev
์•ฝ์†์€ ๊ณต๊ธ‰์ž์™€ ์†Œ๋น„์ž๋ฅผ ๋ฌถ๋Š” ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ์ดํ•ดํ•˜๋ ค๋ฉด async javascript ๋ธ”๋กœ๊ทธ์—์„œ ์ด ํ‚ค์›Œ๋“œ๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ฐœ๊ฒฌ๋˜์—ˆ๋Š”์ง€ ๊ธฐ์–ตํ•˜์‹ญ๋‹ˆ๊นŒ?

์•ฝ์†์€ ์ฝ”๋“œ ์กฐ๊ฐ์—์„œ ์„ฑ๊ณต์ ์ธ ์ถœ๋ ฅ์„ ๋ฐ›์•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ์ถ”์ ํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

Promise์—๋Š” ๋‘ ๊ฐœ์˜ ์ฝœ๋ฐฑ์ด ์žˆ์œผ๋ฉฐ, ๋‘˜ ์ค‘ ํ•˜๋‚˜๋Š” ์ˆ˜์‹ ๋œ ์ถœ๋ ฅ์— ๋”ฐ๋ผ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค. resolve(value) & reject(error).

ํ•ด๊ฒฐ์€ ์„ฑ๊ณต์ ์ธ ์‹คํ–‰์„ ์œ„ํ•œ ๊ฒƒ์ด๊ณ  ๊ฑฐ๋ถ€๋Š” ์ˆ˜์‹ ๋œ ์˜ค๋ฅ˜๋ฅผ ์œ„ํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

const MyPromise=new Promise((resolve, reject)=>{
    const rand=Math.floor(Math.random()*2);
    console.log(rand)
    if(rand===0)
        resolve();
    else
        reject()

})

MyPromise
.then(()=>{console.log("success")})
.catch(()=>{console.log("Error")})





์—ฌ๊ธฐ์„œ ์šฐ๋ฆฌ๋Š” 1 ๋˜๋Š” 2๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” random number ์‚ฌ๋ก€๋กœ ์ž‘์—…ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. .then๋Š” ์„ฑ๊ณต์ ์ธ ์‘๋‹ต์„ ์ฒ˜๋ฆฌํ•˜๊ณ  .catch๋Š” ์˜ค๋ฅ˜๋ฅผ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ์ด๋“ค์€ state ๋ฐ result ๋ผ๋Š” ๋‚ด๋ถ€ Promise ์†์„ฑ์— ์•ก์„ธ์Šคํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
  • ์ƒํƒœ๋Š” ์ˆ˜ํ–‰ํ•ด์•ผ ํ•˜๋Š” ์ž‘์—…์˜ ์ƒํƒœ๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค. ๋ณด๋ฅ˜, ์ดํ–‰ ๋˜๋Š” ๊ฑฐ๋ถ€๋Š” ์„ธ ๊ฐ€์ง€ ์ง€ํ‘œ์ž…๋‹ˆ๋‹ค.
  • ์ฒ˜์Œ์—๋Š” ๊ฒฐ๊ณผ๊ฐ€ ๋น„์–ด ์žˆ์ง€๋งŒ ํ•ด๊ฒฐ๋  ๋•Œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ฑฐ๋‚˜ ๊ฑฐ๋ถ€๋  ๋•Œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค.

  • Only the first call to resolve/reject is taken and once the value for state and result is set it's final. More on promises by javascript.info



    โญ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์ฒ˜์Œ์ด์‹ ๊ฐ€์š”? https://boot.dev/tracks/computer-science์—์„œ ํ›Œ๋ฅญํ•œ ๊ณผ์ •์„ ์‹œ๋„ํ•ด ๋ณด์‹ญ์‹œ์˜ค.

    ์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ