JS 10-3 비동기처리 - async/await

Seungju Hwang·2021년 1월 28일
0

JavaScript

목록 보기
13/13
post-thumbnail

Intro

callback, Promise 보다 개선된 방식으로 비동기 처리를 도와주는 async/await !


🔵 Promise를 통한 비동기 코딩의 문제

function fetchAuthorName(postId) {
  return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
    .then((response) => response.json())
    .then((post) => post.userId)
    .then((userId) => {
      return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
        .then((response) => response.json())
        .then((user) => user.name)
    })
}

fetchAuthorName(1).then((name) => console.log("name:", name))
//결과
// name: Leanne Graham

메서드 체이닝 기법으로 비동기 처리를 하면 다음과 같은 문제가 발생합니다.

  1. 디버깅
    어떤 then 에서 에러가 났는 지 확인하는 게 매우 어려움.
  2. 예외처리
    Promise를 사용하면 catch()를 통해 예외처리를 해야합니다. 이 부분이 비동기코드와 동기코드가 섞여 있으면 문제를 발생하기 쉽습니다.
  3. 들여쓰기
    결국은 중첩, 병렬이 들어가다보니 가독성이 떨어지게 됩니다.

🔵 async/await 키워드를 통한 비동기코딩

ES&에서 async/await 키워드가 추가되었습니다! 비동기코드를 마치 동기코드처럼 보이게 작성할 수 있어요!


async function fetchAuthorName(postId){
  const postResponse = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${postId}`
  )
  const post = await postResponse.json()
  const userId = post.userId
  const userResponse = await fetch(
    `https://jsonplaceholder.typicode.com/users/${userId}`
  )
  const user = await userResponse.json()
  return user.name
}

fetchAuthorName(1).then((name) => console.log('name:',name))
//결과
// name: Leanne Graham

함수선언부에 async 키워드가 있습니다. 그리고 Promise를 리턴하는 모든 비동기 함수 호출부 앞에는 await키워드가 있습니다. 비동기처리처럼 바로 실행이 다음라인으로 넘어가지 않고 결과값을 얻을 수 있을 때까지 기다립니다.

➡ 따라서 동기코드처리와 동일한 흐름으로 코드를 작성할 수 있습니다.

예외처리

async function fetchAuthorName(postId) {
  const postResponse = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${postId}`
  )
  const post = await postResponse.json()
  const userId = post.userId

  try {
    const userResponse = await fetch(
      `https://jsonplaceholder.typicode.com/users/${userId}`
    )
    const user = await userResponse.json()
    return user.name
  } catch (err) {
    console.log("Faile to fetch user:", err)
    return "Unknown"
  }
}

fetchAuthorName(1).then((name) => console.log("name:", name))

동기/비동기 상관없이 try/catch로 일관되게 예외 처리를 할 수 있는 부분도 async/await를 사용했을 때의 이점입니다!!


profile
기록하는 습관은 쉽게 무너지지 않아요.

0개의 댓글