Answer the question
In order to leave comments, you need to log in
Async function is executed multiple times in sql query?
Good day. I have a function that will check the player, he also completed the quest, puts this quest into activated ones and gives out the balance:
var setStatistic = function(type, userid) {
connection.query('SELECT * FROM Quests WHERE Quests.quests <> \'0\' AND Quests.id NOT IN (SELECT questid FROM QuestsActive WHERE QuestsActive.userid = ?) LIMIT 1', [userid]).then(function(questdata) {
if(questdata && questdata[0]) {
connection.query('SELECT COUNT(id) AS quests FROM QuestsActive WHERE userid = ?', [userid]).then(function(result){
var questcount = parseInt(questdata[0].quests, 10),
usercount = parseInt(result[0].quests, 10);
if(usercount >= questcount) {
connection.query('INSERT INTO QuestsActive SET ?', {'questid': questdata[0].id, 'userid': userid}).then(function(result){
updateBalance(questdata[0].prize, userid).then(function(result){
console.log('ok ' + userid + ' type: ' + type);
}).catch(function(error){
console.log(error);
});
}).catch(function(error){
console.log(error);
});
}
}).catch(function(error){
console.log(error);
});
}
}).catch(function(error){
console.log(error);
});
};
Answer the question
In order to leave comments, you need to log in
1. Name variables meaningfully. When there are a lot of requests, it is difficult to understand what result
2 is. Do not write callback hell . For example, use promise.
3. When there are several simultaneous http requests, then by the time of the third SQL, the results of the first two may already be out of date.
Read about isolation levels .
I recommend using advisory locks in PostgreSQL. Or other locations.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question