๐Ÿ‘จโ€๐Ÿ‘ง async/await

๊น€์ฒ ์ค€ยท2022๋…„ 1์›” 21์ผ
0

Javascript

๋ชฉ๋ก ๋ณด๊ธฐ
4/16

async/await : ES8(ECMAScript 2017)์— ๋„์ž…๋œ ํ‚ค์›Œ๋“œ๋กœ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋ฅผ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋ฅผ ์™œ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ• ๊นŒ?
์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ์ฝ”๋“œ๊ฐ€ ์žˆ์„ ๋•Œ ๋ฌด์—‡์ด ๋จผ์ € ์‹คํ–‰๋ ์ง€ ๋ชจ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๋™๊ธฐ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•˜์—ฌ ์ˆœ์„œ๋ฅผ ์ •ํ•ด์คŒ์œผ๋กœ์จ ํ—ท๊ฐˆ๋ฆฌ์ง€ ์•Š๋„๋ก ๋น„๋™๊ธฐํ•จ์ˆ˜๋ฅผ ์ฐจ๋ก€๋กœ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•ด์„œ์ด๋‹ค.

ํ”„๋กœ๋ฏธ์Šค ํ›„์†์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ

const h1 = document.querySelector( "h1" );
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((res) => res.json())
  .then((result) => (h1.textContent = JSON.stringify(result)));

async/await ์‚ฌ์šฉ

const h1 = document.querySelector("h1");

async function fetchtodo() {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const result = await response.json();
  h1.textContent = JSON.stringify(result);
}



  • async/await๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ ์ œ๋„ค๋ ˆ์ดํ„ฐ์™€ ๋น„์Šทํ•˜๊ฒŒ ๊ตฌํ˜„ํ•˜์˜€๋‹ค.
    ์ œ๋„ค๋ ˆ์ดํ„ฐ : ํ•จ์ˆ˜ํ˜ธ์ถœ()์ด ํ•จ์ˆ˜๋ฅผ ์ œ์–ดํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๊ฐ์ฒด

  • async/await๋Š” ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•œ๋‹ค.

  • async๋Š” ์–ธ์ œ๋‚˜ ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    async ํ•จ์ˆ˜๊ฐ€ ๋ช…์‹œ์ ์œผ๋กœ ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๋”๋ผ๋„ ์•”๋ฌต์ ์œผ๋กœ ๋ฐ˜ํ™˜๊ฐ’์„ resolveํ•˜๋Š” ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

  • await๋Š” ํ”„๋กœ๋ฏธ์Šค๊ฐ€ settled ๋œ ์ƒํƒœ(๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๊ฐ€ ์ˆ˜ํ–‰๋œ ์ƒํƒœ)๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ ๋Œ€๊ธฐํ•˜๋‹ค๊ฐ€ settled ์ƒํƒœ๊ฐ€ ๋˜๋ฉด ํ”„๋กœ๋ฏธ์Šค๊ฐ€ resolveํ•œ ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

  • await๋Š” ๋ฐ˜๋“œ์‹œ ํ”„๋กœ๋ฏธ์Šค ์•ž์—์„œ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

async function foo() {
  const a = await new Promise((res) => setTimeout(() => res(1), 3000));
  const b = await new Promise((res) => setTimeout(() => res(2), 2000));
  const c = await new Promise((res) => setTimeout(() => res(3), 1000));
  console.log([a, b, c]); // ์ด 6์ดˆ๊ฐ€ ์†Œ์š”๋œ๋‹ค.
}

foo();

์ด์ฒ˜๋Ÿผ async/await๋Š” ๋น„๋™๊ธฐ ์ฝ”๋“œ๋ฅผ ๋™๊ธฐ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€