직관적인 비동기 처리코드 작성

목표


asyncawait에 대해 알아본다.

async 함수


다음 코드를 살펴보자.

function hello() {
  return "hello";
}

async function helloAsync() {
  return "hello, Async";
}

console.log(hello());
console.log(helloAsync());

결과값은 첫 줄에 hello, 두번째 줄에 Promise 객체로 출력될 것이다. 즉, async 함수는 Promise 객체를 반환한다. 이는 반환값에 .then.catch를 쓸수 있다는 것과 같다.

async function helloAsync() {
  return "hello, Async";
}

helloAsync().then((res) => {
  console.log(res);
});

다음 출력 값은 hello, Async이다. 즉, async 함수의 반환값은 resolve 값과 같다.

await 함수


1초 뒤에 문자열이 출력되도록 만들었다.

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  return delay(1000).then(() => {
    return "hello, Async";
  });
}

helloAsync().then((res) => {
  console.log(res);
});

여기서 await을 사용하여 더 간편하게 코드를 작성할 수 있다.

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function helloAsync() {
  await delay(1000);
  return "hello async";
}

helloAsync().then((res) => {
  console.log(res);
});

await이 붙은 줄은 코드를 동기적으로 수행한다. 즉, delay(1000) 수행이 끝나기 전에는 다음 코드를 실행할 수 없다.

awaitasync function 내에서만 사용이 가능하다.

await을 더 이용하여 다음 코드처럼 비동기함수 내에서 동기적으로 코드를 수행할 수 있다.