Узел Js MySQL несколько вопросов запросов

Я работаю над проектом ввода-вывода и у меня возникла проблема, когда я пытаюсь сделать несколько запросов MySQL в рамках одной функции.

При совпадении выигрыша Расчеты происходят, Mysql выбирает просто не происходит, и выдается ошибка, что объект победителя отсутствует.

Я пытался решить эту проблему несколькими способами: 1) Когда я пытался вложить второй запрос на выборку в первую функциональность результата запроса на выборку - он выдал ошибку Mysql

Ошибка: Невозможно поставить Quit в очередь после вызова quit.

2) Я попытался удалить все conenction.end() и оставить только один в конце функциональности калькуляции. -> Это привело к

Невозможно поставить Query в очередь после вызова quit.

Есть ли у кого-нибудь какие-либо советы, как настроить код таким образом, чтобы я мог размещать запросы один за другим, полагаю, что я упустил некоторые мелкие детали.

if(data.gameStatus == 'calculation'){
        //winner data
        mysqlConnect();
        connection.query('SELECT * FROM users where username = "'+data.winnerData.username+'"', function(err, result){
            if(err){
                getDateTimeNow();
                console.log(err);
                console.log(datetime+' Error occured while calculating game score for'+ data.winnerData.username);
                console.log('============================================================');
            }
            else{
                winner = result;
            }
        });
        //loser data
        connection.query('SELECT * FROM users where username = "'+data.winnerData.username+'"', function(err, result){
            if(err){
                getDateTimeNow();
                console.log(err);
                console.log(datetime+' Error occured while calculating game score for'+ data.loserData.username);
                console.log('============================================================');
            }
            else{
                loser = result;
            }
        });
        // rank calculations
        var gameTime = data.gameTime;

        var winnerPointsBefore = winner[0].points;
        var winnerRank = winner[0].rank;
        var winnerDefuses = data.winnerData.minesDefused;
        var winnerFlags = data.winnerData.fieldsFlagged;
        var winnerId = winner[0].id;
        var winnerUsername = winner[0].username;
        var winnerGamesWon = winner[0].games_won;
        var winnerGamesLost = winner[0].games_lost;
        var winnerCoins = winner[0].coins;

        var timeBonus = 0;
        var rankPointAfterModifier = 0;

        var loserRank = loser[0].rank;
        var loserPointsBefore = loser[0].points;
        var loserDefuses = data.losetData.minesDefused;
        var loserFlags = data.loserData.fieldsFlagged;
        var loserId = loser[0].id;
        var loserUsername = loser[0].username;
        var loserGamesWon = loser[0].games_won;
        var loserGamesLost = loser[0].games_lost;
        var loserCoins = loser[0].coins;

        if(winnerPointsBefore - loserPointsAfter > 700){
            //If pro is facing noob which is 1.5 rank bellow he cannot gain more or less than 15 point
            rankPointAfterModifier = 15;
        }else{
            if(winnerDefuses == 10 && winnerFlags >= winnerDefuses){
                //Game won by defusing all mines -> time bonus calculations depending on rank
                timeBonus = 70 - 10*winnerRank - gameTime;
                if(loserFlags > loserDefuses){
                    loserFalseFlags = loserFlags - loserDefuses;
                    opponentPointReduction = 5 * (loserDefuses - loserFalseFlags);
                    if(opponentPointReduction < 0) {
                        opponentPointReduction = 0;
                    }
                }else{
                    opponentPointReduction = 5 * loserDefuses;
                }
            pointsGained = (winnerDefuses * 5) - opponentPointReduction + timeBonus;
            }else{
                //Game won by opponent exploding(retard lose scenario)
                if(loserFlags > loserDefuses){
                    loserFalseFlags = loserFlags - loserDefuses;
                    opponentPointReduction = 5 * (loserDefuses - loserFalseFlags);
                    if(opponentPointReduction < 0) {
                        opponentPointReduction = 0;
                    }
                }else{
                    opponentPointReduction = 5 * loserDefuses;
                }
                pointsGained = 5 * (winnerDefuses * (winnerFlags / winnerDefuses)) - opponentPointReduction;
            }
            if(winnerRank != loserRank){
                rankPointAfterModifier = -0.2 * (winnerRank-loserRank) * pointsGained;
            }
            else{
                rankPointAfterModifier = pointsGained;
            }
        }
        winnerCoinsEarned = Math.floor(rankPointAfterModifier / 2);
        loserCoinsEarned = Math.floor(rankPointAfterModifier / 5);  
        winnerPointsAfter = winnerPointsBefore + rankPointAfterModifier;
        loserPointsAfter = loserPointsBefore - rankPointAfterModifier;
        // Register game data in sql
        var gameLog = {
            winner_id: winnerId,
            loser_id: loserId,
            winner_name: winnerUsername,
            loser_name: loserUsername,
            winner_defuses: winnerDefuses,
            winner_flagged: winnerFlags,
            loser_defuses: loserDefuses,
            loser_flagged: loserFlags,
            game_time: gameTime,
            rank_exchanged: rankPointAfterModifier,
            winner_coins_gain: winnerCoinsEarned,
            loser_coins_gain: loserCoinsEarned
        }
            connection.query('INSERT INTO gamelog SET ?', gameLog, function(err, result){
                if(err){
                    getDateTimeNow();
                    console.log(err);
                    console.log(datetime+' Error occured while Registering game Log  1337');
                    console.log('============================================================');
                }
                getDateTimeNow();
                console.log(datetime+  "Game result has been registered: "+result.insertId);
                console.log('============================================================');
            });
        //Register data to game history for player
            //winner
            winnerGamesWon++;
            winnerRankNow = 1;
            if(winnerPointsAfter >= 1500){
                winnerRankNow = 2;
            }
            if(winnerPointsAfter >= 1800){
                winnerRankNow = 3;
            }
            if(winnerPointsAfter >= 2100){
                winnerRankNow = 4;
            }
            if(winnerPointsAfter >= 2500){
                winnerRankNow = 5;
            }
            totalWinnerCoins = winnerCoins + winnerCoinsEarned;
            connection.query('UPDATE users SET  games_won = '+winnerGamesWon+', coins = '+totalWinnerCoins+', points ='+winnerPointsAfter+',rank = '+winnerRankNow+' WHERE id = '+winnerId, function(err, result){
                if(err){
                    getDateTimeNow();
                    console.log(err);
                    console.log(datetime+' Error occured while Updating winner rank points  1336');
                    console.log('============================================================');
                }
                getDateTimeNow();
                console.log(datetime+  "Rank point has been updated for: "+ winnerUsername);
                console.log('============================================================');
            });
            //winner
            loserGamesLost++;
            loserRankNow = 1;
            if(loserPointsAfter >= 1500){
                loserRankNow = 2;
            }
            if(loserPointsAfter >= 1800){
                loserRankNow = 3;
            }
            if(loserPointsAfter >= 2100){
                loserRankNow = 4;
            }
            if(loserPointsAfter >= 2500){
                loserRankNow = 5;
            }
            totalLoserCoins = loserCoins + loserCoinsEarned;
            connection.query('UPDATE users SET  games_lost = '+loserGamesLost+', coins= '+totalLoserCoins+', points ='+loserPointsAfter+',rank = '+loserRankNow+' WHERE id = '+loserId, function(err, result){
                if(err){
                    getDateTimeNow();
                    console.log(err);
                    console.log(datetime+' Error occured while Updating winner rank points  1336');
                    console.log('============================================================');
                }
                getDateTimeNow();
                console.log(datetime+  "Rank point has been updated for: "+ winnerUsername);
                console.log('============================================================');
            });
        returnData = {
            loser : {
                username: loserUsername,
                rankPointsBefore: loserPointsBefore,
                rankPointsAfter: loserPointsAfter,
                loserCoinsEarned: loserCoinsEarned
            },
            winner : {
                username: winnerUsername,
                rankPointsBefore: winnerPointsBefore,
                rankPointsAfter: winnerPointsAfter,
                winnerCoinsEarned: winnerCoinsEarned
            },
            totalRankPoints: winnerPointsBefore + loserPointsBefore 
        }
    }

0 ответов

Другие вопросы по тегам