我想查询3个数据库并在结果页面中显示结果,但在查询完成之前会显示此页面。
如何在3次查询完成后才显示结果页面?
我已经尝试过promises,回调函数,async / await和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;
});
}
答案 0 :(得分:0)
您可以尝试在def array_front9(nums):
for i in range(3):
if nums[i]==9:
return True
break
else:
return False
方法中返回一个promise并等待它们,类似于(我省略了非相关代码):
lookup
但是,我更喜欢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