Reputation: 31
I have a task which requires me to store data returned from an sql query into a list in JavaScript. The problem I'm facing is the asynchronous nature of JavaScript (NodeJS). The queries are not being executed in a synchronous order and therefore, the data points are not getting stored in the list in a sequential manner. I tried using promises, but no luck. I'm fairly new to JavaScript and stuck with this problem for around 12 hours now.
I have tried using promises, async.waterfall and other functions within the async module, but none of them could solve this.
query = "SELECT count(*) as users from tb"
query1 = "SELECT count(*) as collats from ct"
var list = [];
var user;
conn.connect().then(function() {
var req = new sql.Request(conn);
req.query(query).then(function (data) {
user = (data.d[0].users);
list.push(user);
})
.catch(function (err) {
console.log(err);
conn.close();
});
req.query(query1).then(function (data) {
list.push(data.d[0].coll);
conn.close();
console.log("After closing second connection the value in list as of now is ",list[0],list[1]);
**strong text**
})
.catch(function (err) {
console.log(err);
conn.close();
});
Expected outcome should be : After closing second connection the value in list as of now is 334,23. // (334 = list[0] and 23 = list[1])
Actual Output: Sometimes it's the same as expected. But in some scenarios,it prints "After closing second connection the value in list as of now is 334, undefined"
That's because of the async nature of Javascript. How do I push the elements in the list in a sequential fashion?
Upvotes: 0
Views: 55
Reputation: 2161
Here are two snippets, the first one does first query then second query then ends. The second one does both queries at the same time, waits for them to finish, and ends.
Both are untested but are the general idea on how to solve your race condition and make your code deterministic.
then()
query = "SELECT count(*) as users from tb"
query1 = "SELECT count(*) as collats from ct"
var list = [];
var user;
conn.connect().then(function() {
var req = new sql.Request(conn);
req.query(query)
.then(function (data) {
user = (data.d[0].users);
list.push(user);
return req.query(query1);
})
.then(function(data){
list.push(data.d[0].coll);
conn.close();
console.log("After closing second connection the value in list as of now is ",list[0],list[1]);
})
.catch(function (err) {
console.log(err);
conn.close();
});
});
query = "SELECT count(*) as users from tb"
query1 = "SELECT count(*) as collats from ct"
var list = [];
var user;
conn.connect().then(async function() {
var req = new sql.Request(conn);
try{
var [data1, data2] = await Promise.all([req.query(query), req.query(query1)]);
list[0] = data1.d[0].users;
list[1] = data2.d[0].coll;
conn.close();
console.log("After closing second connection the value in list as of now is ",list[0],list[1]);
}catch(err){
console.log("Error occured", err);
conn.close();
}
});
Upvotes: 1