[JS] async/await

zzincode·2024년 7월 7일
0

JavaScript

목록 보기
19/24
post-thumbnail

async/await

프로미스의 후속 처리 메서드 없이 마치 동기 처리처럼 프로미스가 처리 결과를 반환

async 함수

  • 명시적으로 프로미스를 반환하지 않더라도 async 함수는 암묵적으로 반환값을 resolve하는 프로미스를 반환
  • await 키워드는 반드시 async함수 내부에서 사용

await 키워드

  • 프로미스가 settled 상태가 될 때까지 대기하다가 settled상태가 되면 프로미스가 resolve한 처리 결과를 반환
  • await 키워드는 반드시 프로미스 앞에서 사용
const getData = async id => {
  const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  const data = await response.json();
  console.log(data)
}

getData(1);

async/await에서 에러 처리 try…catch문

const getData = async id => {
  try{
    const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  	const data = await response.json();
  	console.log(data)
  }catch(err){
    console.error(err);
  }
}

// getData(d); // ReferenceError: d is not defined
getData(1);

+) async 함수 내에서 catch문을 사용해서 에러 처리를 하지 않으면 async함수는 발생한 에러를 reject하는 프로미스를 반환한다
따라서 async함수를 호출하고 Promise.prototype.catch 후속 처리 메서드를 사용해 에러를 캐치할 수도 있음

const getData = async id => {
    const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  const data = await response.json();
  return data;
}

getData(1)
.then(console.log)
.catch(console.error);

에러처리 구현하는 방법

  1. if문이나 단축평가 또는 옵셔널 체이닝 연산자?를 통해 확인해서 처리하는 방법과 에러처리 코드를 미리 등록해 두고 에러가 발생하면 에러처리코드로 점프하도록 하는 방법
  2. try…catch…finally
    • finally 불필요하다면 생략가능
    • catch 생략 가능하지만 catch문이 없는 try문은 의미가 없으므로 생략하지 않음

0개의 댓글