[Node.js] async/await 사용하기

Joney의 SW 공부 블로그·2023년 6월 20일
0

Node.js

목록 보기
3/3

async와 await

callback과 promise와 같이 비동기 처리를 위한 방법

async

  • function 앞에 위치하며, 항상 promise를 반환

await

  • promise가 처리될 때까지 대기
  • then을 사용하지 않고 promise처리가 끝날 때까지 기다렸다가 다음 처리를 할 수 있음

사용해보기

async와 await을 사용하여 promise에서 했던 예시를 구현해보자.
코드는 아래와 같이 구현할 수 있다.

function process(str, ms){
  return new Promise(function(resolve, reject) {
      setTimeout(() => {
          console.log(str)
          resolve();
      }, ms);
  });
};

async function test(){
  console.log('start')
  await process('프로세스1', 1000)
  await process('프로세스2', 500)
  await process('프로세스3', 100)
  console.log('end')
}

test()

위 코드를 실행해 보면 아래와 같은 결과가 출력된다.

start
프로세스1
프로세스2
프로세스3
end



error handling

async와 await를 사용하는 경우의 error handling은 try/catch를 사용해서 구현 가능

function process(str, ms){
  return new Promise(function(resolve, reject) {
      setTimeout(() => {
          console.log(str)
          resolve();
      }, ms);
  });
};

async function test(){
  console.log('start')
  try {
    await process('프로세스1', 1000)
  } catch(err) {
    console.log(err)
  }
  console.log('end')
}

test()
profile
SW 지식 노트 블로그

0개의 댓글