async/await 이란?

웅평·2023년 7월 17일
0

async란?
asynchronous의 줄임말로 비동기를 의미한다
함수 안에 비동기적으로 실행될 부분이 있다는 것을 의미한다
프로미스 객체를 리턴하는 코드앞에 awit를 붙인다

await이란?
await뒤의 코드를 실행하고 그 코드가 리턴하는 프로미스 객체가 fulfilled 또는 rejected 상태가 될 때까지 기다린다
fulfilled상태가 되면 작업 성공 결과를 추출해서 리턴한다

async function fetchAndPrint() {
  console.log(2);
  const response = await fetch('https://googole.com');
  console.log(7);
  const result = await response.text();
  console.log(result);
}

console.log(1);
fetchAndPrint();
console.log(3);
console.log(4);
console.log(5);
console.log(6);

결과

1
2
3
4
5
6
7
리스폰스의 내용

async 함수 안의 코드가 실행되다가 await을 만나면, 일단 await 뒤의 코드가 실행되고, 코드의 실행 흐름이 async 함수 바깥으로 나가서 나머지 코드를 다 실행한다
그 이후로는, await 뒤에 있던 Promise 객체가 fulfilled 또는 rejected 상태가 되면 결과를 리턴한다

catch문과 finally문
rejected상태일 때를 고려

코드 예시

async function fetchAndPrint() {
  try {
  	console.log(2);
    const response = await fetch('https://googole.commmm');
    console.log(7);
    const result = await response.text();
    console.log(result);
  } catch (error) {
  	console.log(error);
  } finally {
  	console.log('finally')
  };
}

console.log(1);
fetchAndPrint();
console.log(3);
console.log(4);
console.log(5);
console.log(6);

일부러 url주소를 틀리게 적고 실행하면

1
2
3
4
5
6
7
에러코드
finally

awit를 쓰지 않을 경우

어떤 값을 리턴하는 경우
1. Promise 객체를 리턴하는 경우

async function fetchAndPrint() {
  return Promise.reject(new Error('Fail'));
}

fetchAndPrint();

async 함수 안에서 Promise 객체를 리턴하는 경우에는 해당 Promise 객체와 동일한 상태와 작업 결과를 가진 Promise 객체를 리턴

  1. Promise 객체 이외의 값을 리턴하는 경우
async function fetchAndPrint() {
  return 3;
}

fetchAndPrint();

async 함수 내부에서 Promise 객체 이외에 숫자나 문자열, 일반 객체 등을 리턴하는 경우에는, fulfilled 상태이면서, 리턴된 값을 작업 성공 결과로 가진 Promise 객체를 리턴

아무 값도 리턴하지 않는 경우

async function fetchAndPrint() {
  console.log('Hello');
}

fetchAndPrint();

함수에서 아무런 값도 리턴하지 않으면 자바스크립트에서 undefined를 리턴
fulfilled 상태이면서, undefined를 작업 성공 결과로 가진 Promise 객체가 리턴

async 함수 내부에서 에러가 발생했을 때

async function fetchAndPrint() {
  throw new Error('Fail');
}

fetchAndPrint();

async 함수 안에서 에러가 발생하면, rejected 상태이면서, 해당 에러 객체를 작업 실패 정보로 가진 Promise 객체가 리턴

참고
코드잇

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

정말 잘 읽었습니다, 고맙습니다!

답글 달기
comment-user-thumbnail
2023년 7월 18일

훌륭한 글이네요. 감사합니다.

답글 달기