# Async & Await

์–ด์‹ฑํฌ ์–ด์›จ์ดํŠธ๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ํŒจํ„ด์˜ ์ตœ์‹  ๋ฌธ๋ฒ•์ž…๋‹ˆ๋‹ค. Promise์™€ Callback์—์„œ ์ฃผ๋Š” ๋‹จ์ ๋“ค์„ ํ•ด๊ฒฐํ•˜๊ณ  ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ๋น„๋™๊ธฐ์  ์‚ฌ๊ณ  ๋ฐฉ์‹์—์„œ ๋ฒ—์–ด๋‚˜ ๋™๊ธฐ์ (์ ˆ์ฐจ์ )์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ค๋‹ˆ๋‹ค.

# ๊ธฐ๋ณธ ๋ฌธ๋ฒ•

async ํ•จ์ˆ˜์˜ ๊ธฐ๋ณธ ๋ฌธ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

async function fetchData() {
  await getUserList();
}

async ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜์˜ ์•ž์— async๋ฅผ ๋ถ™์—ฌ์ฃผ๊ณ  ํ•จ์ˆ˜์˜ ๋‚ด๋ถ€ ๋กœ์ง ์ค‘ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๋กœ์ง ์•ž์— await๋ฅผ ๋ถ™์—ฌ์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค. ์ข€ ๋” ์ •ํ™•ํ•˜๊ฒŒ ๋งํ•˜๋ฉด Promise ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” API ํ˜ธ์ถœ ํ•จ์ˆ˜ ์•ž์— await๋ฅผ ๋ถ™์ž…๋‹ˆ๋‹ค.

# ๊ธฐ๋ณธ ์˜ˆ์ œ

๋‹ค์Œ ์ฝ”๋“œ๋ฅผ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

async function fetchData() {
  var list = await getUserList();
  console.log(list);
}

function getUserList() {
  return new Promise(function(resolve, reject) {
    var userList = ['user1', 'user2', 'user3'];
    resolve(userList);
  });
}

fetchData() ํ•จ์ˆ˜์—์„œ getUserList() ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๋‚˜๋ฉด Promise ๊ฐ์ฒด๊ฐ€ ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ Promise๋Š” ์‹คํ–‰์ด ์™„๋ฃŒ๋œ ์ƒํƒœ(resolve)์ด๋ฉฐ ์‹คํ–‰์˜ ๊ฒฐ๊ณผ๋กœ userList ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ fetchData()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด userList์˜ ๋ฐฐ์—ด์ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

fetchData(); // ['user1', 'user2', 'user3']

# (๋ถ€๋ก) Async & Await ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•œ ๋ฐ”๋ฒจ ํ”Œ๋Ÿฌ๊ทธ์ธ ์„ค์ •

๋ทฐ ์ตœ์‹  CLI ๋„๊ตฌ๋Š” ๋ณ„๋„์˜ ๋ฐ”๋ฒจ ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ์„ค์น˜ํ•˜์ง€ ์•Š์•„๋„ ๋ฐ”๋กœ async & await ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ, ๋ทฐ CLI 2.x ๋ฒ„์ „๋Œ€๋Š” ์•„๋ž˜์™€ ๊ฐ™์€ ์ถ”๊ฐ€ ์„ค์ •์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

  1. ๋‹ค์Œ ๋ฐ”๋ฒจ ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ์„ค์น˜ํ•œ๋‹ค.
npm i babel-plugin-transform-runtime
  1. .babelrc ํŒŒ์ผ์— ์•„๋ž˜์™€ ๊ฐ™์€ ์„ค์ •์„ ์ถ”๊ฐ€ํ•œ๋‹ค.
"plugins": ["transform-runtime"]