-2

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
 });
});

1 Answers1

0

You mix sync and async approach, that's why you get this issues.

I suggest check out this posts to understand difference.

What is the difference between synchronous and asynchronous programming (in node.js)

Synchronous vs Asynchronous code with Node.js

About your problem. Solution is simple. Add callback

getWeather: function(callback) {
    request(config.weatherdomain, function(err, response, body) {
        if (err) {
            callback(err, null)
        } else {
            let weather = JSON.parse(body);
            let returnString = {
                temperature: Math.round(weather.main.temp),
                type: weather.weather[0].description
            }
            callback(null, JSON.stringify(returnString));
       }
    });
}

And now in route

router.get('/', function(req, res, next) {
weatherApp.getWeather(function(err, result) {
     if (err) {//dosomething}
     res.render('index', {
        title: 'Home',
        data: weather
      });
    });
});

Hope this helps.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50
Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24