简体   繁体   English

如何让返回等待 MySQL 连接结束? Node.js

[英]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).我是 Node.js 的新手,我正在 Wix 上测试一些代码,以检查我的数据库在允许创建新帐户之前是否已经存在帐户名称(我目前故意不使用 WHERE 标签用于学习目的) .

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)))欢迎来到 Node.js(以及异步函数(和承诺(和回调)的世界))

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.我已经以“回调”风格编写了这个,但我强烈建议您研究 async/await 类似的东西,以及了解“承诺”如何融入图片中。

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

    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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