【问题标题】:Rewriting Fetch API in Javascript用 Javascript 重写 Fetch API
【发布时间】:2021-08-27 01:42:57
【问题描述】:

我是使用 Javascript API 的新手,我正在尝试了解有关编写 fetch 的不同方法的更多信息。这使用 async await 和 Fetch 类。 我想在没有这个的情况下重写它,看起来更像这样:

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;
  })

目前我有这个,使用 await 和 async,以及 Fetch 类:

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(); const ui = new UI();

我不知道如何使用数据对其进行评估。由于 const ft = new Fetch,我无法理解如何在没有 Fetch 类的情况下重写它并确保 currentVal 使用数据进行评估。感谢您提供任何帮助,我主要只是想了解更多有关 fetch 如何与 API 一起使用的信息。

【问题讨论】:

  • 问题令人困惑,在标题中你说要重写 Fetch API,在文本中你要在没有 Fetch 类的情况下重写代码,你真正需要的根本不清楚.也就是说,重写Fetch API 是一项艰巨的工作,也许你应该找到一个更小的 API 来学习,并结合教程和文档学习 Fetch API ..?
  • 您希望它看起来更像一个函数,其中包含一个不执行的函数,returns 什么也没有。为什么? fetch 工作正常。

标签: javascript javascript-objects fetch-api


【解决方案1】:

这可以像修改 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(function(response){
    let data = response.json();
    console.log(data);
    return data;
  });
}

然后,将对ft.getCurrent 的调用替换为temperature

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

删除ft的创建,实际上,完全删除Fetch类。

temperature的返回类型是Promise,它本身就是response.json()的返回。 Promises 的工作方式,在 then 延续中返回 Promise 会导致对 then 的调用返回 Promise,从而允许这样的链接。

您会注意到:

console.log(data);

temperature 内的行实际上会输出如下内容:

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());
}

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2020-08-15
    • 2016-11-28
    • 2017-09-29
    相关资源
    最近更新 更多