프로미스의 후속 처리 메서드 없이 마치 동기 처리처럼 프로미스가 처리 결과를 반환
const getData = async id => {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
const data = await response.json();
console.log(data)
}
getData(1);
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);
?
를 통해 확인해서 처리하는 방법과 에러처리 코드를 미리 등록해 두고 에러가 발생하면 에러처리코드로 점프하도록 하는 방법