1

尝试在呈现页面之前确保请求已完成

应用程序概述 - 使用代码提交、发出请求、填充结果页面

//索引.js

var response = require('./requestMapping')

// home search page
exports.index = function(req, res){
  res.render('index', { stationDisplay: response.station_id, test: 'rob' });
};

**//post from form to call METAR service
exports.post =('/', function(req, res, next) {
  response.getMETAR(req.body.query,function(){
    res.render('results', {
        stationDisplay: response.station_id,
        test: 'rob'
    });
  });
})**

//索引.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= stationDisplay %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>Enter ICAO code to get the latest METAR</h1>
    <form method="post" action="/">
        <input type="text" name="query">
        <input type="submit">
    </form>
  </body>
</html>

调用 web 服务的模块 - requestMapping.js

/**
 * @author robertbrock
 */
//Webservice XML
function getMETAR(ICAO){

    var request = require('request');
    request('http://weather.aero/dataserver_current/httpparam?datasource=metars&requestType=retrieve&format=xml&mostRecentForEachStation=constraint&hoursBeforeNow=24&stationString='+ICAO, function(error, response, body){
        if (!error && response.statusCode == 200) {
            var XmlDocument = require('xmldoc').XmlDocument;
            var results = new XmlDocument(body);

            console.log(body)
            console.log(ICAO)
            exports.station_id = results.valueWithPath("data.METAR.station_id");
//etc.

        }
    })
}
exports.getMETAR =getMETAR;
4

2 回答 2

1

我看不出你的getMETAR函数实际上需要一个回调函数?我希望它是:

function getMETAR(ICAO, callback) {
    // Do your work
    var station_id = results.valueWithPath("data.METAR.station_id");
    callback(null, station_id); // It's common to use the first arg of the callback if an error has occurred
}

然后调用这个函数的代码可以像这样使用它:

app.post('/', function(req, res) {
    response.getMETAR(req.body.query, function(err, station_id) {
        res.render('results', {stationDisplay: station_id, test: 'rob'};
    });
});

习惯异步编程和回调如何工作需要一些时间,但是一旦你完成了几次,你就会掌握它的窍门。

于 2013-03-30T23:44:52.127 回答
0

没有看到你的代码的其余部分很难猜测,但你的代码应该看起来更像:

app.post('/', function(req, res, next) {
  response.getMETAR(req.body.query,function(){
    res.render('results', {
        stationDisplay: response.station_id,
        test: 'rob'
    });
  });
});
于 2013-03-30T22:23:45.907 回答