简体   繁体   中英

How to make return wait for MySQL connection to end? Node.js

I'm new to Node.js I'm testing some code on Wix to check my database if a account name already exists prior to allowing a new one to be created (I'm purposely not using the WHERE tag at the moment for learning purposes).

Currently the method check account name returns before the connection finishes, not allowing the check to take place properly.

Any help appreciated.

    export function tryToCreateAccount(login, password) 
{
    var mysql = require('mysql');

    var connection = mysql.createConnection({
        host: 'host',
        user: 'user',
        password: 'pass',
        database: 'db'
    });

    if(checkAccountName(login, connection))
    {
        console.log("Name didn't exist.");
    }
    else
    {
        console.log("Name Existed.");
    }
}

function checkAccountName(account_name, connection)
{
    var accountNameAvailable = true;

    connection.connect(function (err)
    {
        if(err) throw err;
        connection.query("SELECT login FROM accounts", function (err, result)
        {
            if (err) throw err;

            for(var i = 0; i < result.length ; i++)
            {
                if(result[i].login == account_name)
                {
                    console.log("Should of been false");
                    connection.end;
                    accountNameAvailable = false;
                }
            }

        });
        connection.end;
    });

    return accountNameAvailable;
}

I figured out why it wasn't doing anything, the next was getting called too late since the connection ended and next was within the connection code block.

const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'host',
    user: 'user',
    password: 'pass',
    database: 'db'
});

export function tryToCreateAccount(login, password) 
{
    checkAccountName(login, connection, function(err, accountNameAvailable)
    {
      if(err || !accountNameAvailable){
        console.log("Name didn't exist.");
      }
      else
      {
        console.log("Name Existed.");
      }
   })
}

function checkAccountName(login, connection, next)
{
    var accountNameAvailable = false;

    connection.connect(function (err)
    {
        if(err) next(err);
        connection.query("SELECT login FROM accounts", function (err, result){
            if (err) next(err);
            for(var i = 0; i < result.length ; i++)
            {
                if(result[i].login == login)
                {
                    accountNameAvailable = true;
                }
            }
            next(null, accountNameAvailable);
            connection.end();
        });
    });
}

Welcome to Node.js (and the world of Async functions (and Promises (and Callbacks)))

I've written this in the "callback" style, but I highly recommend looking into async/await for something like this, as well as understanding how "promises" fit into the picture.

// to test, call tryToCreateAccount('login','pass',function(err,data){console.log(err,data)});

const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'host',
    user: 'user',
    password: 'pass',
    database: 'db'
});
export function tryToCreateAccount(login, password, next) 
{
    checkAccountName(login, connection, function(err, accountNameAvailable){
      if(err || !accountNameAvailable){
        console.log("Name didn't exist.");
        next(err || 'Name didn't exist.')
      }
      else
      {
        console.log("Name Existed.");
        next(null, true)
      }
   })
}

function checkAccountName(account_name, connection, next)
{
    var accountNameAvailable = false;

    connection.connect(function (err)
    {
        if(err) next(err);
        connection.query("SELECT login FROM accounts", function (err, result){
            if (err) next(err);
            for(var i = 0; i < result.length ; i++)
            {
                if(result[i].login == account_name)
                {
                    console.log("Should of been false");
                    connection.end;
                    accountNameAvailable = true;
                }
            }
            connection.end();
            next(null, accountNameAvailable);
        });

    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM