Home Java Script | async await
Post
Cancel

Java Script | async await

๋ชฉ์ฐจ

async await ๐ŸŒŠ

  1. async await๋ž€?

async await

1. async await๋ž€?

  • ๊ฐ„๋‹จํ•˜๊ณ  ๊ฐ€๋…์„ฑ ์ข‹๊ฒŒ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋ฅผ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” async/await๊ฐ€ ๋„์ž…
  • ํ”„๋กœ๋ฏธ์Šค์˜ ํ›„์† ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ ์—†์ด ๋งˆ์น˜ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ํ”„๋กœ๋ฏธ์Šค๊ฐ€ ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Œ
  • async : function ํ‚ค์›Œ๋“œ ์•ž์— ๋ฐฐ์น˜ (async๊ฐ€ ๋ถ™์€ ํ•จ์ˆ˜๋Š” ํ”„๋ผ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , ํ”„๋ผ๋ฏธ์Šค๊ฐ€ ์•„๋‹Œ ๊ฒƒ์€ ํ”„๋ผ๋ฏธ์Šค๋กœ ๊ฐ์‹ธ ๋ฐ˜ํ™˜ํ•จ)
  • await : ๋น„๋™๊ธฐ๋กœ ์ฒ˜๋ฆฌ๋˜๋Š” ๋ถ€๋ถ„ ์•ž์— ๋ฐฐ์น˜ (await ํ‚ค์›Œ๋“œ๋ฅผ ๋งŒ๋‚˜๋ฉด ํ”„๋ผ๋ฏธ์Šค๊ฐ€ ์ฒ˜๋ฆฌ(settled)๋  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆผ) ++ Promise์˜ .then()์„ ํ†ตํ•œ ๋™๊ธฐ ์ฒ˜๋ฆฌ์™€ ๊ฐ™์€ ์—ญํ• 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    //async await
    async function f() {
      let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("์™„๋ฃŒ!"), 1000);
      });
      let result = await promise; // ์›๋ž˜๋ผ๋ฉด, promise.then(()=>{})์„ ํ†ตํ•ด ๋น„๋™๊ธฐ๋ฅผ ๋ฐ›์•„์•ผํ•˜์ง€๋งŒ
      // await ํ‚ค์›Œ๋“œ๋กœ ์ง๊ด€์  ์ด์–ด์กŒ๋‹ค.
      alert(result); // "์™„๋ฃŒ!"
    }
    f();
    

2. promise์™€ async await

  • ์—๋Ÿฌ ํ•ธ๋“ค๋ง
    • Promise ๋ฅผ ํ™œ์šฉํ•  ์‹œ์—๋Š” .catch() ๋ฌธ์„ ํ†ตํ•ด ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ํ•ด์•ผ ํ•˜์ง€๋งŒ,
    • async/await ์€ try / catch๋ฅผ ํ†ตํ•ด ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค
  • ์ฝ”๋“œ ๊ฐ€๋…์„ฑ -Promise์˜ ํ›„์† ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ์ธ .then() ์˜ hell์˜ ๊ฐ€๋Šฅ์„ฑ -async/await ์€ ํ”„๋กœ๋ฏธ์Šค์˜ ํ›„์† ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ ์—†์ด ๋งˆ์น˜ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ํ”„๋กœ๋ฏธ์Šค๊ฐ€ ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ฝ”๋“œ ํ๋ฆ„์„ ์ดํ•ด ํ•˜๊ธฐ ์‰ฌ์›€






์ถœ์ฒ˜

async await
๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์™€ async

This post is licensed under CC BY 4.0 by the author.

Java Script | ํ•จ์ˆ˜์™€ ์ผ๊ธ‰ ๊ฐ์ฒด

HTML | ๋ฐ˜์‘ํ˜•๊ณผ ์ƒ๋Œ€ ๊ธธ์ด ๋‹จ์œ„