강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

이우철님의 프로필 이미지
이우철

작성한 질문수

모던 자바스크립트(ES6+) 심화

4. Fetch 프로세스: JSON 데이터, Blob 파일

throw 대신 return으로 에러를 반환하는 이유가 궁금합니다.

작성

·

480

0

안녕하세요 선생님, 예제로 주신 fetch.js 파일의 try, catch 문에서 throw 대신 return을 사용하신 이유가 궁금합니다.

const fetchData = {
 
  (... 생략)
 
  async main(url, option){
    this.option = Object.assign({}, this.defaultFetch, option);
    this.setSendData();
    try {
      const response = await fetch(url, this.option);
      return response.ok ? await this.convertData(response)
                         : {error: response, errorCode: "OKError"};
    } catch (error){
      //server down
      return {error: error, errorCode: "NetWork"};
    };
  },
 
  (... 생략)
};

저는 fetchData를 다음과 같이 사용할 것 같은데, 이 방식이 맞을까요? 만약 맞다면, 기능은 결국 동일하므로 그냥 단순히 취향 차이인지, 각각의 장단점이 있는지가 궁금합니다.

// 에러를 return했을 때의 예상 코드
fetchData.main(url, option).then((someData) => {
  if (someData.error) {
    // TODO: 에러가 발생했을 때 수행할 작업
  }
});
 
// 에러를 throw했을 때의 예상 코드
fetchData
  .main(url, option)
  .then((someData) => {})
  .catch((error) => {
    // TODO: 에러가 발생했을 때 수행할 작업
  });

퀴즈

What is the main purpose of the Fetch API?

Synchronous File System Access

Asynchronous Communication with the Server

Local Database Management

Direct DOM Element Manipulation

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
이우철님의 프로필 이미지
이우철

작성한 질문수

질문하기