Here is what i going to achieve, i want to have an JSON data that returned from my node.js server is joined based on the value of first mysql queries (array JSON data)
if i just want to execute two mysql queries i just enable multipleStatements: true then the code will be like this :
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);
}
});
});
than the data will showed up two JSON that are separated in two arrays, but what i want to build here is one JSON with multiple array JSON data, which is looked like this :
Sample JSON that i want :
[
{
"product_id":"1",
"product_name":"MX-001",
"product_attachment":[
{
"product_id":"1",
"product_attachment_id":"1",
"file_name":"maxgrand5.jpg",
"file_path":"assets"
}
]
}
]
And here is what i trying to do in my node.js server side code, i trying to use
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);
}));
});
here is my Stored Procedure result which named in 'getProductSingle' :
- product_id = 1
- product_name = MX-001
and here is my second procedure result 'getProductAttachment' :
- product_id = 1
- file_name = maxgrand5.jpg
- file_path = assets
- product_attachment_id = 1
one single product_id can have more than 1 product_attachment_id
how can i get the data joined?
I just updated my question, the problem is the second query is too late when i make the request, i should use promise to make it not late, how to do this?