Javascript

토이프로젝트(3) - 기존 fetch함수를 async/await로 수정

mickey7 2024. 3. 16. 00:21

문제점 분석

  1. fetch 호출에서 오류 처리가 이루어지지 않았다. 네트워크 요청은 실패할 수 있으므로 오류 처리를 추가해야 함
  2. 비트코인 가격을 처리하는 두 번째 fetch 호출은 첫 번째 fetch 호출이 완료된 후에 이루어져야 한다.
    현재 코드에서는 이 작업이 동시에 이루어질 가능성이 있다.

기존코드

//btn클릭 시 date 날짜를 timestamp로 변환

let timestamp = 0;
const res = document.getElementById("authors");
let day = document.getElementById("date");
document.getElementById("btn").addEventListener("click", (e) => {
  timestamp = parseInt(new Date(day.value).getTime() / 1000);
  console.log(timestamp);
  fetch(
    "https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD&ts=" +
      `${timestamp}`
  )
    .then((r) => r.json())
    .then((j) => {
      const btcprice = j.BTC.USD;
      let li = document.createElement("li");
      li.innerHTML = btcprice;
      res.appendChild(li);
      console.log(j);
      fetch(
        "https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD"
      )
        .then((r) => r.json())
        .then((j) => {
          let input = document.getElementById("investment");
        });
    });
});

//순이익/투자 비용 x 100
//다행히 then 안에서 fetch로 다시 불러온 후 then을 사용하면 이전 then 안의 변수는 읽을 수 있다!
// 순이익을 어떻게 구해야 하는가 / 코인 갯수..?

fetch로 복잡하게 결과만 나오게 하다보니 가독성도 떨어진다..

그리고 fetch 함수 호출 문제를 깊게 생각하지 못했던 것 같다. 첫번째 fetch호출 후에 두번째 fetch 호출이 이루어져야 하는데 원하는 출력값만 나와서 그냥 두었던 것 같다.

한마디로 그냥 마구잡이 식으로 결과 출력에만 우선 순위를 뒀던 것 같다.

변경코드

//btn클릭 시 date 날짜를 timestamp로 변환

const res = document.getElementById("authors");
let day = document.getElementById("date");

document.getElementById("btn").addEventListener("click", async () => {
  try {
    const timestamp = parseInt(new Date(day.value).getTime() / 1000);

    //과거 가격
    const btcResponse = await fetch(
      "https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=KRW&ts=" +
        `${timestamp}`
    );
    //과거 가격 불러오기 Error 발생
    if (!btcResponse.ok) {
      throw new Error("Failed to fetch Bitcoin price");
    }
    const btcData = await btcResponse.json();
    const btcprice = Math.floor(btcData.BTC.KRW);

    //현재 가격
    const currentPriceResponse = await fetch(
      "https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=KRW"
    );
    //현재 가격 불러오기 Error 발생
    if (!currentPriceResponse.ok) {
      throw new Error("Failed to fetch current Bitcoin price");
    }

    const currentPriceData = await currentPriceResponse.json();
    const currentPrice = Math.floor(currentPriceData.BTC.KRW);
    const profitPercentage =
      Math.floor(((currentPrice - btcprice) / btcprice) * 100) / 100;
    const investmentInput = document.getElementById("investment");
    const result = investmentInput.value * (1 + profitPercentage);

    //이번 결과 초기화
    while (res.firstChild) {
      res.removeChild(res.firstChild);
    }

    const resultDiv = document.createElement("div");
    resultDiv.innerText = result;
    res.appendChild(resultDiv);
  } catch (error) {
    console.error("An error occured: ", error);
  }
});

async/await을 사용하고 가독성을 고려해서 정리해보니 확실히 더 편한 것 같다. 

에러 처리와 예외 처리를 고려해둔 코드를 염두해 둬야겠다는 생각이 들었다.

 

출력 화면

2024.03.06일에 100을 투자했으면 105원을 얻을 것

프로토타입