0

I just started with node js and I'm in trouble in a procedure. In my code, I get a list of items via json (array) and do a loop that list to see if there is a record in the database or not.

If there is no record in the database, I do an insert if there is I do an update.

The problem is that the system is going too fast over the query and does not wait for the result to see whether or not due to javascript asynchronously.

The need does he wait for the check query to return then continue and finally wait for the insert as well, for the insert must have the answer before continuing the loop "for".

The code would look like this:

var input = JSON.parse (req.param ('data'));
for (var i in input) {
   iCode var = input [i] .codeOSNum;
   qry = 'select count(*) as qtd from table where code = '+iCode; //need wait result from this query
   var connection = new sql.Connection(config);
   var request = new sql.Request(connection);
   request.query(qry, function(err, recordset) {
     if (recordset[0].qtd = 0) {
        //do stuff to insert like: 'insert into blablabla' and need wait return.
     } else {
        //do stuff to update.
     }
  }); //and finally go to next item from loop 'for' and repeat until the end os json array.
}

I use indicated promise, but do not know how to use. I am newbie and desperate.

VtoCorleone
  • 16,813
  • 5
  • 37
  • 51
Asr008
  • 33
  • 1
  • 3
  • 1
    Welcome to Stack Overflow. Please take a few minutes and read http://stackoverflow.com/help/how-to-ask. In your specific case, please add some log output and post the output here or specify exactly what is going wrong with your code. – WeSt Dec 12 '14 at 14:37
  • 1
    Don't be desperate - JavaScript concurrent takes time to nail. Your problem is the for loop (that like you said does not wait for it) - if you go with promises you can use `thenable` chaining (see Bergi's answer [here](http://stackoverflow.com/questions/18386753/) on that). If you want to not use promises (your rest of the code doesn't use them - you can look into the [async library](https://github.com/caolan/async). – Benjamin Gruenbaum Dec 12 '14 at 15:17
  • In addition to the link @Benjamin posted to solve the particular problem, [these few rules of thumb](http://stackoverflow.com/a/25756564/1048572) should get you started with promise development. – Bergi Dec 12 '14 at 15:42
  • basically I need: Step 1: Receive json data Step 2: starts the loop 'for' Step 3: Verify that the record exists and wait for answer Step 3.1: if any do update Step 3.2: If not, I insert and look command completion Step 4: Go to the next record and begin again I can not do at all ... the system does not expect to step 3 of the query response. – Asr008 Dec 12 '14 at 17:00

0 Answers0