I am new to using Javascript APIs and I'm trying to learn more about the different ways to write fetch. This uses the async await and Fetch class. I want to rewrite it without this, to look more like this:
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;
})
Currently I have this, using await and async, and the 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);
});
}
The main issue I'm having, is when I try to rewrite the bottom part, including the currentVal part after: const ft = new Fetch(); const ui = new UI();
I am lost as to how to have it evaluate with the data. Since const ft = new Fetch, I'm having trouble understanding how to re-write this without the Fetch class and make sure currentVal evaluates with the data. Any help is appreciated, I'm mainly just trying to learn more about how fetch works with API.
This could be as simple as modifying your temperature
function to:
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;
});
}
and then, replace the call to ft.getCurrent
with temperature
:
temperature(currentVal).then((data) => {
//call a UI method//
ui.populateUI(data);
//call saveToLS
ui.saveToLS(data);
});
remove the creation of ft
, and, in fact, remove the Fetch
class altogether.
The return type of temperature
is a Promise
, which itself is the return of response.json()
. The way that Promise
s work, returning a Promise
inside the then
continuation causes the invocation of then
to return that Promise
, allowing for chaining like that.
You'll notice that the:
console.log(data);
line inside temperature
will actually output something like:
Promise { <state>: "pending" }
showing that it is, in fact, a Promise
, but this also means that the logging is not very useful, and temperature
could be further simplified to:
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.