Node.js 正在努力让回拨到work express.js

Node.js 正在努力让回拨到work express.js,node.js,express,Node.js,Express,正在尝试确保在呈现页面之前已完成请求 应用程序概述-使用代码提交,提出请求,填充结果页面 //Index.js var response = require('./requestMapping') // home search page exports.index = function(req, res){ res.render('index', { stationDisplay: response.station_id, test: 'rob' }); }; **//post from

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

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

//Index.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'
    });
  });
})**
//Index.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>

如果看不到代码的其余部分,很难猜测,但您的代码应该更像:

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

如果看不到代码的其余部分,很难猜测,但您的代码应该更像:

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

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

习惯异步编程和回调的工作方式需要一些时间,但一旦你做了几次,你就会掌握其中的诀窍。

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

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

谢谢,这需要一点时间来适应,但这确实有帮助。谢谢,这需要一点时间来适应,但这确实有帮助。