0

I am working with node js and postgresql. I tried to insert multiple query at a time.

ArrayList:

var keywordsData =  [ { name: 'demo', count: 69 }, { name: 'healthy', count: '22' }, { name: 'cooking', count: '12' }, { name: 'food', count: '9' }, { name: 'home', count: '9' }, { name: 'organic', count: '7' }, { name: 'live', count: '6' }, { name: 'openmrs', count: '6' }];

Javascript code:

   for (var indexs in keywordsData) {
          var item = keywordsData[indexs].name;
          var count = keywordsData[indexs].count;
          var goalId = 10;

          console.log("first" + indexs);
          if (item.length > 1) {
          client.query("insert into real_keywords(reference_id,keyword,keyword_count) values('" + goalId + "','" + item + "','" + count + "')", function(err, result) {
          console.log("last" + indexs);
          });

          }
    }

Output i am getting like this:

first0
first1
first2
first3
first4
first5
first6
first7
last7
last7
last7
last7
last7
last7
last7
last7

Expected output:

first0
last0
first1
last1
first2
last2
first3
last3
first4
last4
first5
last5
first6
last6
first7
last7

Please anyone can suggest the best way to solve this.

1
  • Ok, this is slightly off topic, so not adding it as an answer. @IyadAssaf answer is correct in regards to async. But you should check out two other bits for your SQL queries 1) Not sure what the size of indexes is, but you can insert all your rows at once. stackoverflow.com/questions/6889065/… 2) You should consider using a prepared statement instead of string concatenation. postgresql.org/docs/9.2/static/sql-prepare.html Commented Jun 10, 2015 at 12:02

1 Answer 1

2

The for loop is synchronous whereas the postgres query you are running is asynchronous - the loop is not waiting for the database callback before iterating.

Probably the easiest way to make this work is to use the async library's each function. For example:

 var async = require('async'),
     values = [{ name: 'demo', count: 69 }, { name: 'healthy', count: '22' }];

async.each(values, function (value, done) {
    client.query('Some query using value.name and value.count', function (err, result) {
        // query is finished
        done(err, result);
    });
 }, function (err) {
      // all queries have finished
 });
Sign up to request clarification or add additional context in comments.

1 Comment

you should use each to loop on array, map is used to return new array

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.