これは私が達成しようとしているものです。私はnode.jsサーバーから返されたJSONデータを最初のmysqlクエリ(配列JSONデータ)の値に基づいて結合したいと思っていますnodejsでpromiseを使って2つのmysqlクエリを実行するには?
私はちょうどmultipleStatements可能にする2つのMySQLクエリ:真は、コードは次のようになり:
app.post( '/製品'、関数(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);
}
});
})。
データが2列に分離された2つのJSONを示したでしょうが、私はここで構築したいことは1 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"
}
]
}
]
そして、ここで私は私がここで
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);
}));
});
を使用しようと、私のNode.jsサーバー側のコードでやろうとすることで名前の私のストアドプロシージャの結果であります'getProductSingle':
- のproduct_id = 1
- PRODUCT_NAME = MX-001
、ここでは私の2番目の手順の結果 'getProductAttachment' です:
- のproduct_id = 1
- file_name = maxgrand5.jpg
- file_path = assets
- product_attachment_id = 1
1つのPRODUCT_IDは、データが加わっどのように私が得ることができる1以上が
をproduct_attachment_id持つことができますか?
私はちょうど私の質問を更新しました、問題は2番目のクエリは、私がリクエストをするには遅すぎる、私はそれを行う方法を遅くするために約束を使用する必要がありますか?
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;
次で:
あなたは必要な結果を返すクエリを作成する必要があります(保存機能付きの可能性があります)。 –
@ UsagiMiyamotoは、関数を保存するとJSONのようなツリーを作成できますそれ?しかし、私はpromise.allを読むことができる –
@ UsagiMiyamotoこんにちは私は約束について私の質問を更新 –