如何在nodejs中使用promise执行两个mysql查询?
下面是我将要实现的,我希望有一个从我的node返回的JSON数据。js服务器根据第一个mysql查询的值(数组JSON数据)进行连接 如果我只想执行两个mysql查询,我只需要启用multipleStatements:true,那么代码如下: 应用程序发布(“/产品”,功能(请求,回复){ })) 然后数据将显示两个JSON,它们在两个数组中分开,但我想在这里构建一个JSON和多个数组JSON数据,如下所示: 我想要的示例JSON:如何在nodejs中使用promise执行两个mysql查询?,mysql,arrays,json,node.js,promise,Mysql,Arrays,Json,Node.js,Promise,下面是我将要实现的,我希望有一个从我的node返回的JSON数据。js服务器根据第一个mysql查询的值(数组JSON数据)进行连接 如果我只想执行两个mysql查询,我只需要启用multipleStatements:true,那么代码如下: 应用程序发布(“/产品”,功能(请求,回复){ })) 然后数据将显示两个JSON,它们在两个数组中分开,但我想在这里构建一个JSON和多个数组JSON数据,如下所示: 我想要的示例JSON: [ { "product_id":"
[
{
"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”中命名的存储过程结果:
我刚刚更新了我的问题,问题是当我提出请求时,第二个查询太迟了,我应该使用promise使其不迟,如何做到这一点?首先我创建了一个查询,其中product\u single table与product\u附件连接,也许您想用
WHERE
子句或带有LIMIT
和OFFSET
的分页机制来限制它:
SELECT ps.product_id, ps.product_name, pa.product_attachment_id,
pa.file_name, pa.file_path
FROM product_single ps
LEFT JOIN product_attachment pa
ON ps.product_id = pa.product_id
ORDER by ps.product_id,pa.product_attachment_id;
在下面的代码中,我将使用调用product\u join\u att
引用此查询
return new Promise(function(resolve, reject) {
var result_products = [];
var result_attachments = [];
var old_id = undefined;
var old_name = undefined;
var new_id = undefined;
var row_index = 0;
connection.query('call product_join_att', function (err, rows, fields) {
if (err) {
reject(err);
return;
} else if (rows.length == 0) {
reject(new Error('No Results found'));
return;
}
while (row_index < rows.length ) {
new_id = rows[row_index].product_id;
if (old_id !== new_id) { // any new line with an new id...
if (typeof old_id !== 'undefined') { // when the old line is existing
result_products.push( // push the product
{"product_id": old_id.toString(),
"product_name":old_name,
"product_attachment": result_attachments
});
}
old_id = new_id; // remember the new_id
old_name = rows[row_index].product_name;// and name
product_attachments = []; // and initialize attachments.
}
product_attachments.push({ // provide the inner attachment informations.
"product_id": new_id,
"product_attachment_id" : rows[row_index].product_attachment_id,
"file_name" : rows[row_index].file_name;
"file_path" : rows[row_index].file_path;
});
row_index++; // and go to the next row.
}
if (typeof old_id !== 'undefined') { // if there are still data
result_products.push( // push the last line also.
{"product_id": old_id.toString(),
"product_name":old_name,
"product_attachment": result_attachments
});
}
} // query
resolve(result_products);
} // end of promise...
返回新承诺(函数(解析、拒绝){
var结果_乘积=[];
var结果_附件=[];
var old_id=未定义;
var old_name=未定义;
var new_id=未定义;
var行指数=0;
connection.query('call product\u join\u att',函数(err、行、字段){
如果(错误){
拒绝(错误);
返回;
}else if(rows.length==0){
拒绝(新错误(“未找到结果”);
返回;
}
while(行索引
我用更简单的解决方案解决了这个问题,但这种方法并不是一种“承诺”的方法,所以,如果你们面临这样的问题,请决定使用哪种方法。因为我不需要很多数据来循环,只需要一个根数组JSON和一维JSON数组,我将这样说:
app.post('/getsingleproduct', function (req, res) {
var product_series = req.body.product_series;
connection.query('call getProductSingle("'+ product_series +'")', function (err, rows, fields) {
if (!err) {
var response = [];
if (rows.length != 0) {
response.push({ 'result': 'success', 'data': rows[0] });
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
}
connection.query('call getProductAttachment("'+ rows[0][0].product_id +'")', function (err, rowsAttachment, fields) {
if (!err) {
if (rowsAttachment.length != 0) {
response[0].data[0]['product_attachment']= rowsAttachment[0];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
res.status(400).send(err);
}
}
});
} else {
res.status(400).send(err);
}
});
});
这是一种非承诺方式,如果您需要承诺方式,请查找@Myonara答案,我认为最好创建一个查询(可能是一个存储函数)hat返回您需要的结果…@UsagiMiyamoto您是否有示例存储函数可以创建这样的JSON树?但我曾经读过promise.all可以that@UsagiMiyamoto嗨,我刚刚更新了我关于Promise的问题,为什么不使用一个查询或存储过程,将两个表中的信息连接起来h结果表的行…@Myonara你能给我看一个生成嵌套JSON的存储过程查询示例吗?谢谢@Myonara我想我可以不用promise方式来完成它,我有下面的代码,但是因为我想用“promise”方式来完成JSON数组树,我有你的答案作为我的解决方案,非常感谢
app.post('/getsingleproduct', function (req, res) {
var product_series = req.body.product_series;
connection.query('call getProductSingle("'+ product_series +'")', function (err, rows, fields) {
if (!err) {
var response = [];
if (rows.length != 0) {
response.push({ 'result': 'success', 'data': rows[0] });
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
}
connection.query('call getProductAttachment("'+ rows[0][0].product_id +'")', function (err, rowsAttachment, fields) {
if (!err) {
if (rowsAttachment.length != 0) {
response[0].data[0]['product_attachment']= rowsAttachment[0];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
response.push({ 'result': 'error', 'msg': 'No Results Found' });
res.status(400).send(err);
}
}
});
} else {
res.status(400).send(err);
}
});
});