快递程序::
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: "xxx",
database: 'test123'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 8084);
app.get('/',function(request,response){
var first, second;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM test1', function(err, rows, fields)
{
console.log('Connection result error '+err);
first = JSON.stringify(rows);
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM test2', function(err, rows, fields)
{
console.log('Connection result error '+err);
second = JSON.stringify(rows);
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'first' : first,
'second' : second
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
我需要在此处进行哪些代码更改
答案 0 :(得分:0)
您可以更改以下功能:
function ( error, results ) {
response.json({
'first' : first,
'second' : second
});
}
到
function ( error, results ) {
// case 1: since results is a js array object you can do following and is recommended
res.json({first: results[0], second: results[0]});
// case 2:else you can do the following thing as well. (Not recommended in this case of async)
/* var jsonObj = JSON.parse('{first :' + first +', second : ' + second + '}');
response.json(jsonObj); */
}
以下是输出:
{
first :[{"_id":1,"name":"devrath","age":24},{"_id":2,"name":"Dheeraj","age":25},{"_id":3,"name":"Vikas","age":26}],
second : [{"_id":1,"place":"Hassan","phone":1},{"_id":2,"place":"Pune","phone":2},{"_id":3,"place":"Delhi","phone":3}]
}
在您的函数中,实际上变量的类型是字符串(而不是对象),因此您需要在发送响应之前将其解析为JSON(如case2)。但实际上你忘记了results
对象本身,其中包含了所有async.series functions
数组中的所有结果,所以你最好采用case 1
中提到的results[0]
来{ {1}}和first
results[1]
(在这种情况下,您可以忽略存储在变量本身,就像您second
一样)
为了您的信息,您需要在回复之前设置first = JSON.stringify(rows);
。如需更多,请查看快递docs
答案 1 :(得分:0)
您不需要stringify
来自MySql驱动程序的结果。此外,您不需要将结果存储到变量中,因为这正是async.js
为您所做的事情。
因此,代码应如下所示:
var tasks = ['test1', 'test2'].map(function (table) {
return function (callback) {
connection.query('SELECT * FROM ' + table, function (err, rows) {
if (err) {
return callback(err);
}
callback(null, rows);
});
}
});
async.series(tasks, function (err, results) {
if (err) {
return res.send(500);
}
res.json({first: results[0], second: results[1]});
});