JavaScript 응용(async & await)

Sujeong K·2022년 8월 21일
0

JavaScript_basic

목록 보기
15/17

asyncawait :
promise를 반환하는 함수(비동기 함수)를 동기적인 함수를 호출한 것처럼 작동하게 하는 키워드

function hello() {
  return "hello";
}

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

console.log(hello()); // hello
console.log(helloAsync()); // Promise{<pending>}
  • 함수 앞에 async를 붙이면 해당 함수는 Promise를 return하는 비동기 처리 함수가 됨
helloAsync().then((res) => console.log(res));
// hello async
  • async 함수 내의 return 값 = 해당 Promise의 resolve의 결과값

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
// ms만큼 기다렸다가 resolve를 호출하고 끝나는 비동기 처리 함수

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


helloAsync().then((res) => console.log(res));
  • delay(3000).then(() => { return "hello async"; }) : then 메소드의 결과값 "hello async"

✍ await을 써서 가독성 좋게 바꿔보자

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

helloAsync().then((res) => console.log(res));
// 3초 후 "hello async" 출력
  • 비동기 함수 앞에 await을 붙이면 마치 동기적인 함수처럼 작동함
  • await이 붙은 함수가 끝나기 전까지 다음 코드를 실행하지 않음
  • await 키워드는 async 키워드가 붙은 함수 내에서만 사용 가능
async function main() {
  const res = await helloAsync();
  // res = helloAsync가 실행된 후 return한 값
  console.log(res);
}

main();
// 3초 후 "hello async" 출력
profile
차근차근 천천히

0개의 댓글