【发布时间】:2019-02-16 12:32:21
【问题描述】:
我在这里发布了一个之前的问题,How to fix a race condition in Node.js/Express. Where my console will update correctly but my webpage doesn't update
基本上我想知道如何让我的代码在我的网页更新之前完成加载。我听说承诺或异步工作,但我无法在我的代码中正确使用它们。我在下面制作了我的代码的简单版本。目前,当我加载我的页面时,我的天气功能已正确更新,但我的 flickr API 在显示结果之前需要再加载两次页面。有人可以告诉我如何使用 Async 或 Promises 来加载我的所有数据并立即更新页面吗?
app.get('/', function (req, res) {
// Render the webpage
res.render('index', {weather: null, headlocation: null, lat: null, long: null, imgLinks: null, WebLinks: null, imgLinksFl: null, restLat: null, restLong: null, restname: null, error: null});
})
// Main Page
app.post('/', function (req, res) {
city = req.body.city; // Grab the users input city
//console.log(weatherSort); // Debugging
weatherSearch(); // Openweather API
filckrSearch(); // Flickr API
res.render('index', {weather: weatherText, headlocation: headLocationText, lat: latLocation, long: longLocation, imgLinks: imageLinks, WebLinks: websiteLinks, imgLinksFl: imageLinksFlick, restLat: latitudeRest, restLong: longitudeRest, restname: restName, error: null});
});
// Weather function
function weatherSearch(){
// API URL
let urlw = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKeyWeather}`
// Send out a request
request(urlw, function (err, response, bodyW) {
// Check for errors
if(err || (JSON.parse(bodyW).cod == '404') || (JSON.parse(bodyW).cod == '401')){
// If errors are found initialize all variables to empty so that it protects from future errors
// in other API functions
} else {
let weather = JSON.parse(bodyW) // Get JSON result
weatherText = `It's ${weather.main.temp} degrees in ${weather.name}! ${weatherSort}: ${weatherInfo}`;
headLocationText = `The City of ${basicLocation}`;
}
});
}
// Flickr API
function filckrSearch(){
// Create a new Flickr Client
var flickr = new Flickr(apiKeyFlickr);
// Search Flickr based on latitude and longitude of city
flickr.photos.search({
lat: latLocation,
lon: longLocation,
radius: 20, // Set radius to 20km
sort: flickrsort // Sort the photos by users selection
}).then(function (res) {
var farmid = res.body.photos.photo[0].farm;
}).catch(function (err) {
console.error('bonk', err); // Catch errors
});
}
【问题讨论】:
标签: javascript html node.js express ejs