节点。js在查询后连接。

时间:2021-01-07 00:13:13

I am trying to write a database manager module in node.js for some of the common queries I am going to use in a server app. I want to test the module. However, my code does not connect to the database before I do the queries. How can I arrange my code in such way, it connects to db before the queries, not after them?

我正在尝试在node中编写一个数据库管理模块。对于服务器应用程序中要使用的一些常见查询,我想测试这个模块。但是,在执行查询之前,我的代码不会连接到数据库。我如何安排我的代码,它在查询之前连接到db,而不是在查询之后?

Code:

var mysql = require('mysql');

var conn = mysql.createConnection(
{
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'mydb'  
});

conn.connect(function(error)
{
    if ( error) throw error;
    console.log('->connected to database');
});

// user as json
getUserData = function(username)
{
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + 
    '\"' , function (error, result, fields)
    {
        if (error) throw error;
        return result; 
    });
}

console.log('result->' + JSON.stringify(getUserData('eness')));

conn.end();

Output:

result->undefined
->connected to database

2 个解决方案

#1


2  

Your getUserData() has nothing to return. Returning result from the query's callback function does not make it the return value of getUserData() as callback is executed asynchronously.

您的getUserData()没有任何返回值。从查询的回调函数返回结果不会使它成为异步执行回调的getUserData()的返回值。

You can't return from an asynchronous function call inside a synchronous function.

您不能从同步函数内的异步函数调用返回。

If you move the console.log() line into the callback, you will see the correct output:

如果将console.log()行移动到回调中,您将看到正确的输出:

getUserData = function(username) {
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
        if (error) throw error;
        console.log('result->' + JSON.stringify(result));
    });
}

getUserData('eness');
conn.end();

If you don't want to put the logic in the query's callback (separate query and business logic):

如果您不想将逻辑放在查询的回调中(单独的查询和业务逻辑):

getUserData = function(username, cb) {
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
        if (error) throw error;
        cb(result)
    });
}

getUserData('eness', function(result) {
    console.log('result->' + JSON.stringify(result));
});
conn.end();

Welcome to callback hell :) Now consider using Promise.

欢迎回到回叫地狱:)现在考虑使用承诺。

#2


0  

This is happening because of the async nature of node.js , the code after conn.connect will not wait for that connection to complete to execute getUserData, therefore since the getUserData operation is not waiting for the connection to happen before executing you're probably having this error. Try the following to fix this for only testing purposes. And if youre using the getUserData function connected to a REST endpoint this will not occur since connection happens when the nodejs app is starting.

这是因为节点是异步的。连接后的代码不会等待该连接完成以执行getUserData,因此,由于getUserData操作并不等待连接在执行之前发生,所以您可能会出现这个错误。请尝试以下方法修复此问题,仅用于测试目的。如果您正在使用连接到REST端点的getUserData函数,这将不会发生,因为连接发生在nodejs应用程序启动时。

conn.connect(function(error)
    {
        if ( error) throw error;
        else console.log('result->' + JSON.stringify(getUserData('eness')));
        console.log('->connected to database');
    });

function getUserData(username)
{
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + 
    '\"' , function (error, result, fields)
    {
        if (error) throw error;
        return result; 
    });
}

conn.end();

#1


2  

Your getUserData() has nothing to return. Returning result from the query's callback function does not make it the return value of getUserData() as callback is executed asynchronously.

您的getUserData()没有任何返回值。从查询的回调函数返回结果不会使它成为异步执行回调的getUserData()的返回值。

You can't return from an asynchronous function call inside a synchronous function.

您不能从同步函数内的异步函数调用返回。

If you move the console.log() line into the callback, you will see the correct output:

如果将console.log()行移动到回调中,您将看到正确的输出:

getUserData = function(username) {
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
        if (error) throw error;
        console.log('result->' + JSON.stringify(result));
    });
}

getUserData('eness');
conn.end();

If you don't want to put the logic in the query's callback (separate query and business logic):

如果您不想将逻辑放在查询的回调中(单独的查询和业务逻辑):

getUserData = function(username, cb) {
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
        if (error) throw error;
        cb(result)
    });
}

getUserData('eness', function(result) {
    console.log('result->' + JSON.stringify(result));
});
conn.end();

Welcome to callback hell :) Now consider using Promise.

欢迎回到回叫地狱:)现在考虑使用承诺。

#2


0  

This is happening because of the async nature of node.js , the code after conn.connect will not wait for that connection to complete to execute getUserData, therefore since the getUserData operation is not waiting for the connection to happen before executing you're probably having this error. Try the following to fix this for only testing purposes. And if youre using the getUserData function connected to a REST endpoint this will not occur since connection happens when the nodejs app is starting.

这是因为节点是异步的。连接后的代码不会等待该连接完成以执行getUserData,因此,由于getUserData操作并不等待连接在执行之前发生,所以您可能会出现这个错误。请尝试以下方法修复此问题,仅用于测试目的。如果您正在使用连接到REST端点的getUserData函数,这将不会发生,因为连接发生在nodejs应用程序启动时。

conn.connect(function(error)
    {
        if ( error) throw error;
        else console.log('result->' + JSON.stringify(getUserData('eness')));
        console.log('->connected to database');
    });

function getUserData(username)
{
    conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + 
    '\"' , function (error, result, fields)
    {
        if (error) throw error;
        return result; 
    });
}

conn.end();