TIL. 42 await & async

Minjae Choiยท2021๋…„ 8์›” 11์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
11/20

๐Ÿ“‘ await, async

async์™€ await๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๋ฌธ๋ฒ• ์ค‘ ํ•˜๋‚˜์ด๋‹ค. ๊ธฐ์กด์˜ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ๋ฐฉ์‹์˜ ๋‹จ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๋Š” ๊ฒƒ๊ณผ ์ฝœ๋ฐฑ์ง€์˜ฅ์—์„œ ๋ฒ—์–ด๋‚  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ฃผ๊ณ , ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ์‚ด๋ ค์ค€๋‹ค.


๊ธฐ๋ณธ ํ˜•ํƒœ

const ํ•จ์ˆ˜๋ช… = async() => {
  await ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ์ฝ”๋“œ
}
  • ์ผ๋ฐ˜์ ์œผ๋กœ axios์™€ ๊ฐ™์€ ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” API ํ˜ธ์ถœ ํ•จ์ˆ˜์— ์ฃผ๋กœ ์“ฐ์ธ๋‹ค.
const asyncCall = async() => {
  const data = await fetch()
  
  if (data.id === 1) {
    console.log(data.name)
  }
}
  • ์œ„ ์ฝ”๋“œ์—์„œ๋Š” fetch๊ฐ€ ํ˜ธ์ถœ๋˜๊ณ  data๋ฅผ ๋ฐ›์•„์˜ค๋ฉด if๋ฌธ์œผ๋กœ ๋„˜์–ด๊ฐ„ ํ›„ ์ฝ˜์†”์ด ์ถœ๋ ฅ๋œ๋‹ค.

์˜ˆ์™ธ ์ฒ˜๋ฆฌ(try catch)

  • ํ”„๋กœ๋ฏธ์Šค์—์„œ .catch()๋ฅผ ์‚ฌ์šฉํ–ˆ๋˜ ๊ฒƒ์ฒ˜๋Ÿผ async & await์—์„œ๋„ ๋น„์Šทํ•˜๊ฒŒ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค.

  • error ๊ฐ์ฒด์— ๋‚ด์šฉ์ด ๋‹ด๊ธฐ๊ธฐ ๋•Œ๋ฌธ์— ์œ ํ˜•์— ๋งž๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ณ , ํ†ต์‹  ์˜ค๋ฅ˜์™€ ๊ฐ„๋‹จํ•œ ํƒ€์ž… ์˜ค๋ฅ˜ ๋“ฑ ์ผ๋ฐ˜์ ์ธ ์˜ค๋ฅ˜๋„ ์žก์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

  • try ๋‚ด๋ถ€์—๋Š” ์„ฑ๊ณต ๊ด€๋ จ ๋กœ์ง๋งŒ ์žˆ๊ณ , catch ๋‚ด๋ถ€์—๋Š” ์‹คํŒจ ๊ด€๋ จ ๋กœ์ง๋งŒ ์žˆ๋‹ค.

const asyncCall = async() => {
  try {
    const data = await fetch()
  
    if (data.id === 1) {
      console.log(data.name)
    }
  } catch(error) {
    console.log(error);
  }
}

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