[Javascript] async/await에 대해 알아보자

kaya·2023년 11월 27일

Javascript

목록 보기
7/13

async/await이란?

비동기 코드를 동기 코드처럼 작성할 수 있게 도와주는 문법이다

  • ES2017에 도입된 새로운 키워드

async

  • 비동기 처리가 필요한 함수 앞에 붙는 키워드
    • 일반 함수, 익명 함수, 클래스 메소드 모두 다 붙을 수 있다
  • 리턴값: Promise 객체
    ➡️ 프로미스가 아닌 것을 반환해도 프로미스로 감싸서 리턴한다
async function f() {
  return 10  // 프로미스가 아님
}

let v = f()
console.log(v)
// v는 프로미스 객체이다
// Promise {<fulfilled>: 10}
	// >[[Prototype]]: Promise
	// >[[PromiseState]]: "fulfilled"
	// > [[PromiseResult]]: 10

await

  • async 함수 안에서만 동작한다
    ➡️ async 밖에서 쓰면 SyntaxError 발생

  • Promise.then보다 가독성이 좋다

// Promise.then 사용
function promiseThen(url) {
	let response = fetch(url)
    return response
}

promiseThen('https://api.github.com/users/kaya53')
  .then(res => console.log(res))
// async/await 사용
async function asyncAwait(url) {
	let response = await fetch(url)
	if (response.status === 200) {console.log(response)} 
  	else {throw Error}
}

asyncAwait('https://api.github.com/users/kaya')
  • 두 함수의 결과는 같다


예외 처리

1. if ~ else 사용

  • 위에 작성한 예시처럼 응답 객체의 http status code가 200일 때와 200이 아닐 때로 나누어서 예외 처리를 할 수 있다

2. try ~ catch 사용

  • await 이 던진 에러를 try ~ catch를 통해 잡을 수 있다
  • try 문에서 에러를 throw 하지 않으면 catch는 어떤 에러도 받지 못함
    ➡️ 200이 아닌 status code를 받아도 에러라고 인식하지 않음
    ➡️ 이게 axios의 편한 점이다, axios는 http status code가 200이 아니면 .catch, catch 문 같은 에러 처리로 넘긴다
    ➡️ 하지만 비동기 코드에 http 통신 코드만 있는 건 아니니까! (axios는 http 통신을 돕는 라이브러리이다)
async function asyncAwait(url) {
  try {
  	let response = await fetch(url)
    if (response.status !== 200) {
    	throw new Error('요청이 실패하였습니다.')  // catch로 요청 던지기
    }
	return response
  } catch(err) {
    console.log(err)
  }
	
}

asyncAwait('https://api.github.com/users/djoeijowjiof')

3. async 함수 외부에서 .catch로 체이닝

  • async함수 내부의 에러 처리 코드를 함수 밖으로 빼서 .catch에서 처리할 수도 있다.
async function asyncAwait(url) {
  let response = await fetch(url)
  if (response.status !== 200) {
    throw new Error('요청이 실패하였습니다.')  // catch로 요청 던지기
  return response
}

asyncAwait('https://api.github.com/users/djoeijowjiof')
  .catch(err => console.log(err))
  • async가 아닌 함수에서 async함수를 호출해서 에러 처리를 할 때 .catch 처리할 수 있다
async function asyncAwait(url) {
  let response = await fetch(url)
  if (response.status !== 200) {
    throw new Error('요청이 실패하였습니다.') 
  }
  return response
}

function f(url) {
  asyncAwait(url)
    .then(res => console.log(res))
  	.catch(err => console.log(err))
}
f('https://api.github.com/users/kaya53')

참고 페이지

profile
🏟 튼튼한 성은 튼튼한 벽돌로부터

0개의 댓글