我正在創建一個簡單的 Web 應用程式,它從三個 Web api 異步獲取資料。一個用于位置,一個用于天氣,一個用于庫存影像。我的檔案如下:
索引.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
</head>
<body>
<div id="app">
<div >
Weather Journal App
</div>
<form id="userInfo">
<div >
<label for="city">Enter City here</label>
<input type="text" id="city" placeholder="enter city here" required>
</div>
<div >
<label for="date">Enter departure date</label>
<input type="datetime-local" id="date" required>
<button id="submitBtn" type="submit"> Generate </button>
</div>
</form>
<div >
<div >Details</div>
<div>
<img id="city-pic" src="" alt="我想在異步函式中使用for回圈和javascript中的“thens”">
</div>
<div id="entryHolder">
<div><b>Temperature for next 16 days:</b></div>
<ul id="entries">
<div id="temp"></div>
<div id="time"></div>
</ul>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
應用程式.js:
const present = new Date();
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const city = document.getElementById("city").value;
const departure = document.getElementById("date").value;
const [depart_date, depart_time] = departure.split("T")
const [depart_year, depart_month, depart_day] = depart_date.split("-")
const [depart_hour, depart_minute] = depart_time.split(":")
const future = new Date(depart_year, depart_month - 1, depart_day, depart_hour, depart_minute);
if (city !== "" || departTime !== "" || future < present) {
document.getElementById("time").innerHTML = `Departure in ${Math.ceil((future - present) / 3600000 / 24)} days`
getCity(geoURL, city, geoUsername)
.then(function (data) {
return getWeather(weatherURL, weatherKey, data["geonames"][0]['lat'], data["geonames"][0]['lng'])
}).then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
}).then(function () {
return receiveWeatherData()
}).catch(function (error) {
console.log(error);
alert("Please enter a valid city and a valid time");
})
getPictures(city, pixabayURL, pixabayKey)
.then(function (picsData) {
const total = picsData['hits'].length
const picIndex = Math.floor(Math.random() * total)
return postPictureData("/addPicture", { pic: picsData['hits'][picIndex]["webformatURL"] })
})
.then(function () {
return receivePictureData()
}).catch(function (error) {
console.log(error);
alert("No pictures found")
})
}
})
const getCity = async (geoURL, city, geoUsername) => {
const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
try {
const cityData = await res.json();
return cityData;
}
catch (error) {
console.log("error", error);
}
}
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
console.log(newData)
return newData;
}
catch (error) {
console.log(error);
}
}
const receiveWeatherData = async () => {
const request = await fetch("/allWeather");
try {
const allData = await request.json()
const node = document.createElement("li");
const textnode = document.createTextNode("DATE: " allData['datetime'] "\t" "TEMPERATURE: " allData['temp']);
node.appendChild(textnode);
document.getElementById("entries").appendChild(node);
}
catch (error) {
console.log("error", error)
}
}
const getWeather = async (weatherURL, weatherKey, lat, lon) => {
const res = await fetch(`${weatherURL}&lat=${lat}&lon=${lon}&key=${weatherKey}`);
try {
const weatherData = await res.json();
return weatherData;
}
catch (error) {
console.log("error", error);
}
}
const getPictures = async (city, pixabayURL, pixabayKey) => {
const query = city.split(" ").join(" ");
const res = await fetch(`${pixabayURL}key=${pixabayKey}&q=${query}`);
try {
const picsData = await res.json();
return picsData;
}
catch (error) {
console.log("error", error)
}
}
const receivePictureData = async () => {
const request = await fetch("/allPictures");
try {
const allData = await request.json()
document.getElementById("city-pic").src = allData['pic'];
}
catch (error) {
console.log("error", error)
}
}
const postPictureData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
pic: data.pic
})
});
try {
const newData = await response.json();
return newData;
}
catch (error) {
console.log(error);
}
}
server.js:
// Setup empty JS object to act as endpoint for all routes
cityData = {};
weatherData = {};
picturesData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('dist'));
app.use(express.static('website'));
app.get("/all", function sendData(req, res) {
res.send(cityData);
})
app.get("/allWeather", function sendWeather(req, res) {
res.send(weatherData);
})
app.get("/allPictures", function sendPictures(req, res) {
res.send(picturesData);
})
app.post("/addWeather", (req, res) => {
weatherData['temp'] = req.body.temp;
weatherData['datetime'] = req.body.datetime;
res.send(weatherData);
})
app.post("/addPicture", (req, res) => {
picturesData['pic'] = req.body.pic;
res.send(picturesData);
})
// Setup Server
app.listen(3000, () => {
console.log("App listening on port 3000")
console.log("Go to http://localhost:3000")
})
服務器使用 node、express、cors 和 body-parser 作為創建它的工具。
我沒有包含 api 密鑰或用戶名。現在我需要遍歷從 api 回傳的天氣資料(獲取 16 天的資料)。編碼 :
.then(weatherData => {
return postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
應該使用“i”變數來遍歷某個位置的所有可能的 16 個條目。現在,如果用 0 代替“i”運行應用程式,它只會給出第二天的溫度。我想獲取 16 天的天氣資料并將其附加到檔案中的 html 'ul' 中。有人可以指導我。這是我需要在 11 月 10 日之前完成的專案的最后一步!
編輯:
我嘗試使用它并用 forLoop() 代替“thens”,但出現錯誤:
const forLoop = async () => {
for (i = 0; i < 16; i ) {
try {
coords = await getCity(geoURL, city, geoUsername)
weatherData = await getWeather(weatherURL, weatherKey, coords["geonames"][0]['lat'], coords["geonames"][0]['lng'])
await postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
await receiveWeatherData(i);
}
catch (error) {
console.log(error);
// alert("Please enter a valid city and a valid time");
}
}
}
錯誤是:“16app.js:156 TypeError: Cannot read properties of undefined (reading 'lat') at forLoop (app.js:150:89)”
uj5u.com熱心網友回復:
可以使用Array.map()接收到的天氣資料創建一系列承諾,并且可以使用Promise.all(). 回傳的輸出將是接收到的溫度資訊陣列。請看下面的代碼
(PromiseLikeObject)
.then(weatherData => {
const promiseCollection = weatherData['data'].map(d => postWeatherData("/addWeather", { temp: d.temp, datetime: d.datetime }));
return Promise.all(promiseCollection);
});
uj5u.com熱心網友回復:
如果我理解正確,我認為您可以映射資料并將其顯示在 DOM 中,只需將其調整為您收到的陣列。
const postWeatherData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
temp: data.temp,
datetime: data.datetime
})
});
try {
const newData = await response.json();
let entryHolder = document.getElementById("entryHolder");
const weather = newData.map((data, index) => {
return `<ul id="entries">
<div id="temp">${data.temp}</div>
<div id="time">${data.time}</div>
</ul>`
}).join('')
entryHolder.innerHTML = weather
}
catch (error) {
console.log(error);
}
}
uj5u.com熱心網友回復:
我已經用 for 回圈修復了它:
const forLoop = async () => {
for (i = 0; i < 16; i ) {
try {
const city = await document.getElementById("city").value;
const coords = await getCity(geoURL, city, geoUsername)
const weatherData = await getWeather(weatherURL, weatherKey, coords["geonames"][0]['lat'], coords["geonames"][0]['lng'])
postWeatherData("/addWeather", { temp: weatherData['data'][i]['temp'], datetime: weatherData['data'][i]['datetime'] })
receiveWeatherData(i)
}
catch (error) {
console.log(error);
// alert("Please enter a valid city and a valid time");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521273.html
