正在等待 node.js 中的 HTTP 请求

Waiting for an HTTP request in node.js

我知道其他人问过这个问题,我需要使用回调,但我不太确定应该如何将它们与我的代码集成。

我正在使用 node.js 和 express 来制作一个网站,在页面加载时我希望网站去获取天气,等待响应然后加载页面。

我的'WeatherApp'代码如下:

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

我当前的页面路由:

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

您混合使用同步和异步方法,这就是您遇到此问题的原因。

我建议查看此帖子以了解差异。

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

Synchronous vs Asynchronous code with Node.js

关于你的问题。解决方法很简单。添加回调

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

现在在路上

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

希望对您有所帮助。