我想做这件简单的事情。请任何人帮助我这个。任何肯定的答案将不胜感激。我的简单问题是如何将最终数组打印到浏览器。我试图将其显示到浏览器但无法这样做。请帮助我。我是系统的新手。
var http = require('http');
var mysql = require('mysql');
http.createServer(function(req, res) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'DB_USER',
password : 'DB_PASS',
database : 'DB_NAME',
});
connection.connect();
var resp = [];
async.parallel([
function(callback){
setTimeout(function(){
soap.createClient(url, function(err, client) {
client.setSecurity(new WSSecurity('USER_NAME', 'PASSWORD'));
client.SubmitMessage(strContent1, function(err, result) {
resp.push(result.message.payload.unit_of_business_results['premium_details']);
});
});
}, 200);
},
function(callback){
setTimeout(function(){
soap.createClient(url, function(err, client) {
client.setSecurity(new WSSecurity('USER_NAME', 'PASSWORD'));
client.SubmitMessage(strContent2, function(err, result) {
resp.push(result.message.payload.unit_of_business_results['premium_details']);
});
});
}, 100);
},
function(callback){
setTimeout(function(){
soap.createClient(url, function(err, client) {
client.setSecurity(new WSSecurity('USER_NAME', 'PASSWORD'));
client.SubmitMessage(strContent3, function(err, result) {
resp.push(result.message.payload.unit_of_business_results['premium_details']);
});
});
}, 100);
}
],
// optional callback
function(err, results){
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
res.writeHead(200);
res.end(JSON.stringify(resp));
}).listen(8020);
答案 0 :(得分:0)
将响应的发送移至productQuery.on('end')
docs:https://github.com/felixge/node-mysql/#streaming-query-rows
var http = require('http');
var mysql = require('mysql');
http.createServer(function(req, res) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'DB_USER',
password : 'DB_PASS',
database : 'DB_NAME',
});
connection.connect();
var prod = {};
var productsFinished = false;
var productQuery = connection.query('SELECT * FROM tbl_product 1') ;
productQuery.on('result', function (prod_rows) {
prod[prod_rows.product_id] = prod_rows;
});
var employer = {};
var employerFinished = false;
var employerQuery = connection.query('SELECT * FROM tbl_employer 1') ;
employerQuery.on('result', function (empl_rows) {
employer[empl_rows.employer_id] = empl_rows;
});
var sendIfFinished = function () {
if(productsFinished && employerFinished) {
res.writeHead(200);
res.end(JSON.stringify(prod)); // or whatever you want to send.
}
}
productQuery.on('end', function () {
productsFinished = true;
sendIfFinished();
});
employerQuery.on('end', function () {
employerFinished = true;
sendIfFinished();
});
}).listen(8020);