[JavaScript] async, await

Peter·2022년 3월 9일
0
post-thumbnail

비동기 프로그래밍

Promise를 사용해 비동기 처리가 가능하다. 콜백 패턴에 비해서 가독성과 콜백헬로부터 벗어날 수 있는 좋은 방법이긴 하지만 async, await를 통해 좀 더 가독성이 좋게 만들어줄 수 있다

함수에 async를

function hello() { return "Hello" };
hello();
  • 일반적인 함수로써 "Hello"를 리턴하게 된다
async function hello() { return "Hello" };
hello();

const hello = async() => { return "Hello" };

let hello = async function() { return "Hello" };
hello();
  • 함수 앞에 async를 붙이면 함수는 Promise를 리턴하게 된다
  • 화살표 함수엔 인자 앞에 async를 붙인다
  • 변수에 함수를 선언할때도 앞에 async를 붙여주게 된다.
hello().then((value) => console.log(value))
  • Promise는 후처리 메소드를 통해서 비동기 함수에 대한 처리를 할 수 있다.

비동기에 await를

// 기존 promise 처리
fetch('coffee.jpg')
.then(response => response.blob())
.then(myBlob => {
  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
})
.catch(e => {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});
// async, await를 사용한 promise 처리
async function myFetch() {
  let response = await fetch('coffee.jpg');
  let myBlob = await response.blob();

  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}

myFetch()
.catch(e => {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});
  • 자바스크립트 런타임이 await키워드를 확인해 비동기 코드를 일시 중지한다.
  • 비동기 함수가 결과를 반환할때까지 기다리게 함
  • 실제는 then과 같은 원리로 작동되지만 모든 줄들이 동기코드로 보이게 한다는 장점이 있음

async, await의 오류 처리

async function myFetch() {
  try {
    let response = await fetch('coffee.jpg');

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    let myBlob = await response.blob();
    let objectURL = URL.createObjectURL(myBlob);
    let image = document.createElement('img');
    image.src = objectURL;
    document.body.appendChild(image);

  } catch(e) {
    console.log(e);
  }
}

myFetch();
  • try, catch를 통해 오류를 처리할 수 있다
  • catch 에 e 인자를 통해 try과정에서 코드가 뱉은 에러를 콘솔로 출력할 수 있다.

async, await의 단점

  • await를 통해 동기적으로 promise를 실행하기 때문에 코드실행이 느려질 수 있다(총 시간은 같으나 먼저 처리할 틈을 주지 않음)
  • 하지만 DOM 렌더와 같은 이유로 인해 call stack에 틈을 줘야한다.
  • 이 경우 느린 비동기 작업과 빠른 비동기 작업이 문제를 완화시킨다.

slow-async-await

async function timeTest() {
  await timeoutPromise(3000);
  await timeoutPromise(3000);
  await timeoutPromise(3000);
}
  • await를 사용한다면 해당줄이 모두 마무리 되면 다음 코드로 넘어간다
  • 따라서 모든 작업이 완료되기 까지 9초의 시간이 걸리게 된다

fast-async-await

async function timeTest() {
  const timeoutPromise1 = timeoutPromise(3000);
  const timeoutPromise2 = timeoutPromise(3000);
  const timeoutPromise3 = timeoutPromise(3000);

  await timeoutPromise1;
  await timeoutPromise2;
  await timeoutPromise3;
}
  • promise는 변수에 할당되는 동시에 작업을 시작하고
  • await를 통해 마무리를 확인한다
  • 따라서 3초 정도의 시간에서 작업이 완료되게 된다
profile
컴퓨터가 좋아

0개의 댓글