【发布时间】:2018-02-01 19:28:00
【问题描述】:
这是我要实现的目标,我希望根据第一个 mysql 查询的值(数组 JSON 数据)加入从我的 node.js 服务器返回的 JSON 数据
如果我只想执行两个 mysql 查询,我只需启用 multipleStatements: true 那么代码将是这样的:
app.post('/product', function (req, res) {
connection.query('call getProductList; call rowCountTotal', function (err, rows, fields) {
if (!err) {
var response = [];
if (rows.length != 0) {
response.push({ 'result': 'success', 'data': rows });
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
});
数据将显示两个分隔在两个数组中的 JSON,但我在这里要构建的是一个带有多个数组 JSON 数据的 JSON,如下所示:
我想要的 JSON 示例:
[
{
"product_id":"1",
"product_name":"MX-001",
"product_attachment":[
{
"product_id":"1",
"product_attachment_id":"1",
"file_name":"maxgrand5.jpg",
"file_path":"assets"
}
]
}
]
这是我在 node.js 服务器端代码中尝试做的事情,我尝试使用
Promise.all (i think this code i should use right?) :
return new Promise(function(resolve, reject) {
Promise.all(connection.query('call getProductSingle("'+ product_series +'")', function (err, rows, fields) {
if (!err) {
var response = [];
if (rows.length != 0) {
response.push({ 'result': 'success', 'data': rows });
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
}
connection.query('call getProductAttachment("'+ rows[0][0].product_id +'")', function (err, rowsAttachment, fields) {
if (!err) {
console.log("second query");
if (rowsAttachment.length != 0) {
response.push({'product_attachment': rowsAttachment });
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
}
}
});
console.log("outside second query");
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
console.log("last");
if (err) {
return reject(err);
}
resolve(res);
}));
});
这是我在“getProductSingle”中命名的存储过程结果:
- product_id = 1
- product_name = MX-001
这是我的第二个程序结果“getProductAttachment”:
- product_id = 1
- file_name = maxgrand5.jpg
- file_path = 资产
- product_attachment_id = 1
一个 product_id 可以有多个 product_attachment_id
我怎样才能让数据加入?
我刚刚更新了我的问题,问题是我提出请求时第二次查询为时已晚,我应该使用promise让它不迟到,如何做到这一点?
【问题讨论】:
-
您应该创建一个查询(可能是一个存储函数)并返回您需要的结果......
-
@UsagiMiyamoto 你有示例存储函数可以创建这样的 JSON 树吗?但我曾经读过 promise.all 可以做到这一点
-
@UsagiMiyamoto 嗨,我刚刚更新了关于承诺的问题
-
你为什么不使用查询或存储过程,它正在连接两个表中的信息。有了它,您可以遍历该结果表的行...
-
@Myonara 你能告诉我一个存储过程查询示例来生成嵌套 JSON 吗?
标签: mysql arrays json node.js promise