async, await 알아보기

2022. 3. 30. 00:45·TECH

async

async 비동기 함수의 사용법은 function앞에 async키워드를 써주면 됩니다.

async가 반환하는 값은 Promise가 됩니다.

반환된 Promise를 then이나 catch로 받을 수 있습니다.

let hello = async () => { return 'hello'}
hello
    .then((value) => console.log(value))
    .catch((err) => console.log(err));

 

await

순차적으로 실행되어야 하는 비동기 함수가 있는 경우는 해당 비동기 함수 앞에 await 키워드를 써줍니다.

그러면 await를 넣어준 비동기 함수가 fulfil될 때까지 중단하고 결과를 반환합니다.

await는 async function안에서만 사용할 수 있습니다.

async function myFetch() {
  let response = await fetch('coffee.jpg');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.blob();
}

myFetch().then((blob) => {
  let objectURL = URL.createObjectURL(blob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}).catch(e => console.log(e));

 

await, async 작동방식

async, await는 Promise와 비슷하지만

큰 다른점은 Promise는 then을 사용하여 response를 반환하지만 await를 사용하면 변수에 반환할 수 있습니다.

await 키워드는 자바스크립트 런타임이 이 라인에서 비동기 코드가 일시 중지하여 비동기 함수 호출이 결과를 반환할 때까지 기다립니다.

그러나 외부의 다른동기 코드는 실행될 수 있도록 합니다.

 

async, await의 큰 장점은 then체이닝이 줄어들고, 동기 코드처럼 보이기 때문에 가독성이 좋다는 점입니다.

 

오류 처리하기

catch블럭을 then블럭 뒤에 위치시키면 async함수 호출 Promise체인에서 발생하는 오류도 잡을 수 있습니다.

async function myFetch() {
  let response = await fetch('coffee.jpg');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.blob();
}

myFetch().then((blob) => {
  let objectURL = URL.createObjectURL(blob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
})
.catch((e) =>
  console.log(e)
);

 

await Promise.all

async, await는 Promise상위에 만들어져 있어서 Promise의 모든 기능을 사용할 수 있다.

Promise.all과 같이 await Promise.all도 순서를 보장하지 않기 때문에 순차적으로 실행되어야 하는 promise를 실행할 때 주의해야 합니다.

let values = await Promise.all([coffee, tea, description]);

'TECH' 카테고리의 다른 글

redux개념 정리  (0) 2023.02.16
tsconfig.json 기본세팅, d.ts, JSDoc  (0) 2023.02.14
Typescript 기초개념 정리  (0) 2023.02.14
프론트개발시 CORS 오류와 해결방법!  (0) 2022.03.20
Promise에 대해 알아보자!  (0) 2021.09.26
'TECH' 카테고리의 다른 글
  • tsconfig.json 기본세팅, d.ts, JSDoc
  • Typescript 기초개념 정리
  • 프론트개발시 CORS 오류와 해결방법!
  • Promise에 대해 알아보자!
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • 분류 전체보기 (73)
      • TECH (22)
      • NOTE (40)
      • DAILY (7)
      • javascript (1)
      • 알고리즘 (0)
  • 블로그 메뉴

    • 홈
    • TECH
    • NOTE
    • DAILY
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    웹브라우저구성
    커머스프로젝트
    styled-components
    call signatures
    함수와 메서드차이
    배열요소순서
    타입스크립트
    theme-provider
    git배포
    JavaScript
    reat-head
    Array.sort()
    TypeScript
    reduxtoolkit
    redux
    React
    d.ts
    react state management
    slidesPerGroup
    global-style
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
ssund
async, await 알아보기
상단으로

티스토리툴바