Reputation: 1799
I received some information using html form tags
post={count:[1,2,3]}
the information collected is "post"
exports.log_create_process = function(request, response){
var _url = request.url;
var queryData = url.parse(_url, true).query;
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
var title = post.title;
var description = post.description;
var query=``;
for(var i=0; i<post.length; i++){
db.query(`INSERT INTO stock_log(count) VALUES (${post[i}.count);`,function(error, result){
response.end();
});
}
});
}
My goal is to send queries three times. Assuming the table was initially empty. After the log_create_process has completed the table should look like this:
| count|
| 1 |
| 2 |
| 3 |
Upvotes: 0
Views: 118
Reputation: 5564
In your example, you will receive the response just after the first insert because db.query
is asynchronous.
So, if you want to insret your 3 records, you can either insert them with one query, like the following :
const sqlStatement = "INSERT INTO stock_log(count) VALUES ?";
const values = post.count;
db.query(sqlStatement, [values], function (err, result) {
if (err) response.status(500).send("server error");
response.end();
});
OR perform multiples queries, but wait until they are finished to respond.
use a db library that offers promises, like node-promise-mysql
:
// here we assume that db.query returns a Promise.
const queryPromisesArray = post.count.map(p => db.query(`INSERT INTO stock_log(count) VALUES (${p});`));
Promise.all(queryPromisesArray).then(values => {
response.end();
});
Hope it helps,
best regards
Upvotes: 1