问题描述
我是使用 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 配合使用的信息。
解决方法
这可能就像将您的 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()
的返回。 Promise
的工作方式,在 Promise
延续中返回 then
会导致调用 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());
}