TECH

async, await 알아보기

ssund 2022. 3. 30. 00:45

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]);