I know other people have asked this question, and that I need to use callbacks but I'm not quite sure as to how I should integrate them with my code.
I'm using node.js with express to make a website, and on page load I want the site to go and grab the weather, wait for the response and then load the page with it.
My 'WeatherApp' code is as follows:
const config = require('./config');
const request = require('request');
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = {
getWeather: function() {
request(config.weatherdomain, function(err, response, body) {
if (err) {
console.log('error:', error);
} else {
let weather = JSON.parse(body);
let returnString = {
temperature: Math.round(weather.main.temp),
type: weather.weather[0].description
}
return JSON.stringify(returnString);
}
});
}
}
And my current routing for a page:
router.get('/', function(req, res, next) {
var weather;
weather = weatherApp.getWeather();
res.render('index', {
title: 'Home',
data: weather
});
});