V
V
vetsmen2017-08-29 15:12:34
MySQL
vetsmen, 2017-08-29 15:12:34

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);
  });

};

However, I encountered such a problem that if it is called 3 times in a row on the server, then the check for the presence of an activated quest does not work and the balance is issued 3 times. How to be in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Korobkov, 2017-08-29
@vetsmen

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 question

Ask a Question

731 491 924 answers to any question