簡體   English   中英

在 Javascript 中重寫獲取 API

[英]Rewriting Fetch API in Javascript

我是使用 Javascript API 的新手,我正在嘗試了解有關編寫 fetch 的不同方法的更多信息。 這使用異步等待和獲取 class。 我想在沒有這個的情況下重寫它,看起來更像這樣:

function hi() {

  function temperature(input) {
  const myKey = "c3feef130d2c6af1defe7266738f7ca0";
  const api = `https://api.openweathermap.org/data/2.5/weather? 
q=${input}&lang=en&&appid=${myKey}&units=metric`;

  fetch(api)
  .then(function(response){
      let data = response.json();
      console.log(data);
      return data;
  })

目前我有這個,使用等待和異步,以及 Fetch class:

function hi() {
  class Fetch {

    async getCurrent(input) {
      const myKey = "c3feef130d2c6af1defe7266738f7ca0";
      //make request to url
      const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather? 
  q=${input}&lang=en&&appid=${myKey}&units=metric`
      );

      const data = await response.json();
      console.log(data);
      return data;
    }}
  // ui.js

  class UI {
    constructor() {
      this.uiContainer = document.getElementById("content");
      this.city;
      this.defaultCity = "London";
    }

    populateUI(data) {
      //de-structure vars

      //add them to inner HTML

      this.uiContainer.innerHTML = `
      
   <div class="card mx-auto mt-5" style="width: 18rem;">
              <div class="card-body justify-content-center">
                  <h5 class="card-title">${data.name}</h5>
                  <h6 class="card-subtitle mb-2 text-muted">Highs of 
${data.main.temp_max}. Lows of ${data.main.temp_min}</h6>
                  <p class="card-text ">Weather conditions are described 
 as: ${data.weather[0].description}</p>
                  <p class="card-text ">Feels like: 
${data.main.feels_like}</p>

                  <p class="card-text ">Wind speed: ${data.wind.speed} 
m/s</p>
              </div>
          </div>
          `;
    }

    clearUI() {
      uiContainer.innerHTML = "";
    }

    saveToLS(data) {
      localStorage.setItem("city", JSON.stringify(data));
    }

    getFromLS() {
      if (localStorage.getItem("city" == null)) {
         return this.defaultCity;
  
      } else {
        this.city = JSON.parse(localStorage.getItem("city"));
      }
      return this.city;
    }

    clearLS() {
      localStorage.clear();
    }}


  //inst classes// original capstone.js starts here

  const ft = new Fetch();
  const ui = new UI();

  const search = document.getElementById("searchUser");
  const button = document.getElementById("submit");
    button.addEventListener("click", () => {
      const currentVal = search.value;

     // document.querySelector('#temperature-value').innerHTML = 
`${currentVal}`; // added this

      ft.getCurrent(currentVal).then((data) => {
        //call a UI method//
        ui.populateUI(data);
        //call saveToLS
       ui.saveToLS(data);
      });
    });

    //event listener for local storage

   window.addEventListener("DOMContentLoaded", () => {
      const dataSaved = ui.getFromLS();
      ui.populateUI(dataSaved);
    });
    }

我遇到的主要問題是當我嘗試重寫底部部分時,包括之后的 currentVal 部分: const ft = new Fetch(); 常量 ui = 新 UI();

我不知道如何用數據對其進行評估。 由於 const ft = new Fetch,我無法理解如何在沒有 Fetch class 的情況下重寫它,並確保 currentVal 使用數據進行評估。 感謝您提供任何幫助,我主要只是想了解有關 fetch 如何與 API 一起使用的更多信息。

這可以像修改你的temperature function 一樣簡單:

function temperature(input) {
  const myKey = "<REDACTED>";
  const api = `https://api.openweathermap.org/data/2.5/weather?q=${input}&lang=en&appid=${myKey}&units=metric`;

  return fetch(api).then(function(response){
    let data = response.json();
    console.log(data);
    return data;
  });
}

然后,用temperature替換對ft.getCurrent的調用:

temperature(currentVal).then((data) => {
  //call a UI method//
  ui.populateUI(data);
  //call saveToLS
  ui.saveToLS(data);
});

刪除ft的創建,實際上,完全刪除Fetch class。

temperature的返回類型是Promise ,它本身就是response.json()的返回。 Promise的工作方式,在then延續中返回Promise導致調用then返回Promise ,允許像這樣的鏈接。

您會注意到:

console.log(data);

線內temperature實際上將 output 類似於:

Promise { <state>: "pending" }

表明它實際上是一個Promise ,但這也意味着記錄不是很有用, temperature可以進一步簡化為:

function temperature(input) {
  const myKey = "<REDACTED>";
  const api = `https://api.openweathermap.org/data/2.5/weather?q=${input}&lang=en&appid=${myKey}&units=metric`;

  return fetch(api).then(r => r.json());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM