JS 중급 | async, await

uoah·2023년 2월 10일
0

자바스크립트

목록 보기
32/33
post-thumbnail

🚀 오늘의 학습 목표

  • async
  • await
  • then / async, await
  • try...catch문
  • Promise.all

17. async, await

promisethen 형식으로 호출하는 것보다 가속성이 좋아진다.

17.1. async

함수 앞에 async 를 입력하면 promise 를 반환한다.

async function getName(){
  return 'mike';
}

console.log(getName()); 

// Promise {<fulfilled>: 'mike'}

then 을 사용하면 값을 반환한다.

getName().then((name) => {
    console.log(name);
});

// mike

return 반환값이 promise 면? 해당 값을 그대로 사용한다.

async function getName(){
    return Promise.resolve('tom');
}

getName().then((name) => {
    console.log(name);
});

// tom

함수 내에서 예외가 발생하면 rejected 상태의 promise 가 반환된다.
rejected 이기 때문에 catch 로 확인 가능하다.

async function getName(){
    return new Error('err..');
}

getName().catch((err) => {
    console.log(err);
});

/*
Promise {<fulfilled>: Error: err..
    at getName (<anonymous>:2:12)
    at <anonymous>:1:1}
*/

17.2. await

await 키워드는 async 함수 내부에서만 사용 가능하다.
(일반 함수에서 사용하면 에러 발생)

function getName(name) {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res(name);
    }, 3000);
  });
};

async function showName(){
  const result = await getName('uoah velog 입니다.');
  console.log(result);
  alert(result);
};

showName();
alert('반갑습니다.');

  • alert('반갑습니다') 먼저 실행
  • showName 은 getName 에서 resolve 된 값을 3초 기다렸다(await) 실행

이전 시간에 배웠던 예제를 asyncawait 로 변경하여 보자.

const f1 = () => {
  return new Promise ((res, rej) => {
    setTimeout(()=>{
      res('1번 주문 완료');
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise ((res, rej) => {
    setTimeout(()=>{
      res('2번 주문 완료');
    }, 2000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise ((res, rej) => {
    setTimeout(()=>{
      res('3번 주문 완료');
    }, 3000);
  });
};

17.3. then

f1()
.then((res) => f2(res))
.then((res) => f3(res))
.then((res) => console.log(res))
.catch(console.log);

17.4. async, await

console.log('시작');
async function order() {
  const result1 = await f1();
  const result2 = await f2(result1);
  const result3 = await f3(result2);
  console.log(result3);
  console.log('종료');
}

order();

then 을 사용하는 것보다 가독성이 좋다.


17.5. try...catch문

rejected 일 때는 try...catch문을 사용한다.

📍 rejected 일 때

  • promise ➡️ catch
  • async, await ➡️ try...catch 문
const f1 = () => {
  return new Promise ((res, rej) => {
    setTimeout(()=>{
      res('1번 주문 완료');
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej(new Error('err...'));
    } ,2000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise ((res, rej) => {
    setTimeout(()=>{
      res('3번 주문 완료');
    }, 3000);
  });
};

f2 가 rejected 일 때, try...catch문을 사용하면 에러를 찍고 이후 작업을 처리한다.

console.log('시작');
async function order() {
  try{
    const result1 = await f1();
    const result2 = await f2(result1);
    const result3 = await f3(result2);
    console.log(result3);
  } catch(e) {
    console.log(e);
  }
  console.log('종료');
}

order();


17.6. Promise.all

console.log('시작');
async function order() {
  try{
    const result = await Promise.all([f1(), f2(), f3()]);
    console.log(result);
  } catch(e) {
    console.log(e);
  }
  console.log('종료');
}

order();

async, await 함수 내부에서도 비동기 함수를 병렬로 실행할 수 있다.

0개의 댓글

관련 채용 정보