async & await

Beom·2023년 1월 5일
0

자바스크립트 101

목록 보기
9/9

async

promise를 더 가독성 좋게 만들어준다

async function hello(){
	return 'hello async';
}

결과로 Promise{pending}이 출력됨 -> .then 사용가능한 것을 알 수 있다

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

결과는 hello async가 출력됨


await

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

async function helloAsync() {
  // return delay(3000).then(() => {
  //   return "hello Async";
  // });
  await delay(3000);
  return "hello async";
}

async function main() {
  const res = await helloAsync();
  console.log(res);
}

main();

await 을 비동기함수 호출 앞에 붙이면 비동기 함수가 동기처럼 사용 가능

0개의 댓글