티스토리 뷰
1. 목표
- acync, await 함수를 이용하여 예제 함수를 리팩토링하고 싶음.
2. 모르는 것
- acync, await 가 비동기 함수를 동기적으로 변환하는 과정이라는 것을 알고 있음.
- 예제 문서
function loadJson(url) {
return fetch(url).then((response) => {
if (response.status == 200) {
return response.json();
} else {
throw new HttpError(response);
}
}); //fetch의 status 가 200이면 json()를 리턴하고, 아니면 오류를 리턴한다
}
를
async function loadJson(url){
await fetch(url)
await response ()=>{ if (response.status === 200) {
return response.json();}
}
}
까지 작성하긴 했는데... 이게 맞나 싶고, await 뒤에 promise 객체가 온다는 것을 알고 있지만 promise 객체가 정확히 어떤 형태로 들어가는 지는 모르겠음. promise 객체가 resole,reject를 받는 것 까진 알고 있음.
3. 해본 것
console.log(loadJson);을 찍어봤을 때
Uncaught SyntaxError: Malformed arrow function parameter list (at 숙제.js:11:5)
이와 같은 에러 메세지가 뜸.
4. 튜터님 솔루션
async function loadJson(url){
await fetch(url)
까지는 잘 썼음. 그런데 예제를 보면
return fetch(url).then((response) => {
에서 .then이 fetch(url)이 return 하는 값을 인자로 받아서 response로 넣는 걸 알 수 있음. 따라서 fetch의 return 값을 인자로 만들어 넣어주기 위해 const로 변수를 선언하여 response로 전달하는 과정이 필요함.
async function loadJson(url){
const response = await fetch(url);
또한 예제에서 response의 값을 json()함수를 사용해 return 하므로 그 값을 최종적으로 return 하기 위해 새 변수 선언이 또 필요함.
async function loadJson(url){
const response = await fetch(url);
if (response.status == 200) {
const newresponse = await response.json();
return newresponse;
const로 newresponse변수를 선언해주고 return해 주었음.
하지만 if - else 구문은 어떻게 하느냐? 맥락에 따라 넣으면 될 것 같음.
async function loadJson(url){
const response = await fetch(url);
if (response.status == 200) {
const newresponse = await response.json();
return newresponse;
} else {
throw new Error(response);
}
if - else 구문을 넣으면서 async 함수를 쓴다면 try-catch 구문이 필요함. try의 값이 error가 뜨면 catch가 그걸 받아 에러 메세지를 개발자에게 전달해 주는 식.
async function loadJson(url){
try {
const response = await fetch(url);
if (response.status == 200) {
const newresponse = await response.json();
return newresponse;
} else {
throw new Error(response);
}
} catch (error) {
}
}
코드 완성.
+)리팩토링은 코드 양을 줄이는 것 말고도 가독성 있게 변환하는 목표도 있다고 하심.
throw는 아직은 안 배운 코드라 크게 신경쓰지는 말 것.