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.