我想查询3个数据库并在结果页面中显示结果,但此页面在查询完成之前显示。
如何在完成3个查询后才能显示结果页面?
我尝试过promises、回调函数、异步/等待和python的spawnSync,但都不起作用。
任何帮助都将不胜感激。
谢谢!
代码如下:
//Import libraries
const express = require('express');
const path = require('path');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const app = express();
//Load forms
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
//Load static elements
app.use(express.static(__dirname + '/public'));
//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function(req,res){
res.render('search.ejs');
});
app.post('/results', function(req,res){
var products = req.body.products;
var countries = req.body.countries;
price_data = lookup('prices', products, countries);
description_data = lookup('descriptions', products, countries);
other_data = lookup('other', products, countries);
table_data = get_table_data(price_data, description_data, other_data);
res.render('results.ejs', {'table_data': table_data});
//THIS IS THE PROBLEM. THIS PAGE IS RENDERED BEFORE THE 3 LOOKUPS ARE FINALIZED SO IT DISPLAYS NO SEARCH RESULTS
});
function lookup(type, products, countries) {
var spawn = require('child_process').spawn;
var py = spawn('python', [type + '_lookup.py']);
var data = [products, countries];
var python_output_string ='';
py.stdin.write(JSON.stringify(data));
py.stdin.end();
py.stdout.on('data', function(data) {
python_output_string = python_output_string + data;
});
py.stdout.on('end', function() {
console.log(python_output_string);
return python_output_string;
});
}
发布于 2018-06-03 04:45:01
您可以尝试在lookup
方法中返回一个promise并等待它们,类似于(我省略了不相关的代码):
app.post('/results', async (req, res) => {
// ...
price_data = await lookup('prices', products, countries);
description_data = await lookup('descriptions', products, countries);
other_data = await lookup('other', products, countries);
res.render('results.ejs', { table_data: table_data });
});
function lookup(type, products, countries) {
// ...
return new Promise((res, rej) => {
py.stdout.on('end', function() {
res(python_output_string);
});
});
}
但是,我更倾向于使用Promise.all
方法:
app.post('/results', async (req, res) => {
// ...
Promise.all(
lookup('prices', products, countries),
lookup('descriptions', products, countries),
lookup('other', products, countries)
)
.then(values => get_table_data(...values)) // [price_data, description_data, other_data]
.then(table_data => res.render('results.ejs', { table_data }));
});
https://stackoverflow.com/questions/50660953
复制相似问题