0

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   |

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.