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.

RSKMR
  • 1,812
  • 5
  • 32
  • 73
  • 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. http://stackoverflow.com/questions/6889065/inserting-multiple-rows-in-mysql 2) You should consider using a prepared statement instead of string concatenation. http://www.postgresql.org/docs/9.2/static/sql-prepare.html – Alex Hornbake Jun 10 '15 at 12:02

1 Answers1

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
 });
IyadAssaf
  • 308
  • 5
  • 9