async-await의 return 값

QT-HH·2021년 11월 9일
3

JavaScript

목록 보기
1/5

async-await은 promise 객체를 return한다.
하지만 promise객체가 아닌 원하는 response데이터로 받을 수도 있다.

async-await

async-await은 promise요청을 할 때 비동기 처리를 쉽게 해주는 문법이다.
promise가 응답할 때까지 기다려서 동기적으로 코드가 작동할 수 있게 해준다.
당연하겠지만 promise가 아닌 다른 비동기요청은 async-await을 쓸 수 없다.


return 값

const childFunc = async () => {
  await new Promise(r => setTimeout(r, 1000))
  return 'hihi'
}

위와 같은 함수가 있을 때,

const parentFunc = async () => {
  try {
    const res = childFunc()
    return res
  } catch {
    return 'error!'
  }

이 코드에서 parentFunc를 실행시키면 'hihi'가 아닌 promise값을 return한다.
왜냐면 parentFunc안에 있는 childFunc에다가 await을 안걸어줘서
return되는걸 기다리지 않고 pending상태의 promise객체를 res가 참조하는 곳에 저장하기 때문이다.

다만

const parentFunc = async () => {
  try {
    return childFunc()
  } catch {
    return 'error!'
  }

이렇게 바로 return 해주는 경우는 childFunc가 에러없이 작동했을 경우에 'hihi'를 return하지만 에러가 난다해도 'error!'를 return하지 않고 childFunc의 에러를 return한다.

그러므로

const parentFunc = async () => {
  try {
    return await childFunc()
  } catch {
    return 'error!'
  }

이와 같은 형태로 만들어줘야한다.
참고로 parentFunc도 async 함수이므로 return값을 'hihi'로 받고싶다면 await을 붙이고 불러야한다.



참고



플젝을 하다가 갑자기 함수가 promise를 리턴해주길래 뭐지싶어서 찾아봤다.
기본적인 것도 모르고 쓰고있었다.
사실 아직 완전히 이해한건 아니다.
공부해야쥐

profile
FE 초짜

0개의 댓글