node.js - 努力让回调工作express.js

标签 node.js express

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

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

//索引.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;

最佳答案

我看不出您的 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'};
    });
});

需要一些时间来适应异步编程以及回调的工作方式,但是一旦您完成了几次,您就会掌握它的窍门。

关于node.js - 努力让回调工作express.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15724046/

相关文章:

javascript - 使用 Passport js 保护 Node js 中的路由

node.js - Nodemon express

javascript - 在 Express 中设置默认响应 header

node.js - 在 Angular2 应用程序的前端存储对象实例数据是可以接受的做法吗?

node.js - 在express和mongoose中隐藏早于今天的事件日期

node.js - 如何从作为库运行的 postgraphile 获取查询结果

node.js - 服务器上的起始 Node

javascript - Express.js - 监听关机

javascript - Heroku:将 Node 更新到最新版本

javascript - 无法在 node-cron 调度方法中获取数据