gpt4 book ai didi

node.js - 在 REST API 中合并 2 个查询的输出

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:37 25 4
gpt4 key购买 nike

我正在使用 node.js restify 模块。我有一个 REST API,它以 json 格式输出单个 MySQL 查询的结果。这是API的代码;

var rest_api_get_list = function (app, url_name) {
function respond(req, res, next) {
var door_mac = req.query.door_mac;

var connection = own_mysql.getMySQL_connection();

var query_str =
"SELECT doors.mac_addr, " +
"sensors.sensor_type " +
"FROM sensors " +
"WHERE (doors.mac_addr = ?) "
;

var query_var = [door_mac];

var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
//throw err;
console.log(err);
logger.info(err);
}
else {
res.send(rows);
}
});
return next();
}

app.get(url_name, respond);
};

假设我有另一个类似这样的查询;

    var query_str_2 =
"SELECT knobs.mac_addr, " +
"furniture.furniture_type " +
"FROM furnitures" +
"WHERE (knobs.mac_addr = ?) "
;

我想合并 2 个 MySQL 查询 query_strquery_str_2 的输出,并让 REST API 以 json 格式返回结果。如何才能做到这一点?

更清楚地说,我正在考虑代码做这样的事情;

var rest_api_get_list = function (app, url_name) {
function respond(req, res, next) {
var door_mac = req.query.door_mac;

var connection = own_mysql.getMySQL_connection();

var query_str =
"SELECT doors.mac_addr, " +
"sensors.sensor_type " +
"FROM sensors " +
"WHERE (doors.mac_addr = ?) "
;

var query_var = [door_mac];

var query = connection.query(query_str, query_var, function (err, rows_output_1, fields) {
//if (err) throw err;
});

var query_str_2 =
"SELECT knobs.mac_addr, " +
"furniture.furniture_type " +
"FROM furnitures" +
"WHERE (knobs.mac_addr = ?) "
;

var query_2 = connection.query(query_str_2, query_var, function (err, rows_output_2, fields) {
//if (err) throw err;

});

//How to display json output of rows_output_1 and rows_output_2?

return next();
}

app.get(url_name, respond);
};

编辑:我开始悬赏以吸引使用 Promises 的答案。

最佳答案

用于管理异步控制流的模块 - 如 async - 可以帮助您。

例如:

function respond(req, res, next) {

var door_mac = req.query.door_mac;
var connection = own_mysql.getMySQL_connection();
var query_var = [door_mac];

async.parallel([
function (callback) {

var query_str =
"SELECT doors.mac_addr, " +
"sensors.sensor_type " +
"FROM sensors " +
"WHERE (doors.mac_addr = ?) "
;
connection.query(query_str, query_var, callback);
},
function (callback) {

var query_str_2 =
"SELECT knobs.mac_addr, " +
"furniture.furniture_type " +
"FROM furnitures" +
"WHERE (knobs.mac_addr = ?) "
;
connection.query(query_str_2, query_var, callback);
}
], function (error, results) {

// results[0] => result for query_str
// results[1] => result for query_str_2
// ... return next() or whatever
})
}

关于node.js - 在 REST API 中合并 2 个查询的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com