简体   繁体   English

节点JS异步数据库调用

[英]Node JS Asynchronous Database Calls

I am having issues getting node to make a database call without proceeding despite the database function has not returned a value. 尽管数据库函数没有返回值,但是在获取节点以进行数据库调用而不进行操作时遇到问题。

Here is the basic http server code: 这是基本的http服务器代码:

var http = require('http');

http.createServer(function (request, response) {

response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-origin': '*' // implementation of CORS
});

response.end("ok");
;
}).listen(8080,'0.0.0.0');

Using the request.on('data') function, I am able to decode JSON from requests and proceed that to make a database call: 使用request.on('data')函数,我能够从请求中解码JSON并继续进行数据库调用:

request.on('data', function (chunk) {
    var json = JSON.parse(chunk);
    var id = parseInt(json["id"]);
    response.end(callDatabase(id));
});

The database function goes something like this: 数据库函数如下所示:

function callDatabase(id) {
    var result;
    var connection = mysql.createConnection(
        {
            host        :   '192.168.1.14',
            user        :   'root',
            password    :   '',
            database    :   'test'
        }
    );

    connection.connect();
    var queryString = 'SELECT name FROM test WHERE id = 1';

    connection.query(queryString, function(err, rows, fields) {
        if (err) throw err;

        for (var i in rows) {
            result = rows[i].name;
        }
    });
    connection.end();
    return result;
    }
}

However under testing, this proves that I am doing it wrong. 然而,在测试中,这证明我做错了。 I am aware that I probably want to be using the node asynchronous module, which I have tired. 我知道我可能想要使用节点异步模块,我已经厌倦了。 I have also tried using the waterfall method, as well as parallel and many other tutorials online. 我也尝试过使用瀑布方法,以及在线并行和许多其他教程。 I feel that the request.on function should be in parallel, then the database call async, so whilst node is waiting for the response from the database server, it is free to get on with any other requests, leaving the queued time to a minimum. 我觉得request.on函数应该是并行的,然后数据库调用async,所以当node等待来自数据库服务器的响应时,它可以继续使用任何其他请求,将排队时间保持在最低限度。

Please inform me if I have miss-understood any of the concepts of node js. 如果我错过了解节点js的任何概念,请通知我。

You are returning result and closing the connection before the query has returned it's value from the db. 在查询从db返回值之前,您将返回result并关闭连接。 Place that code inside the callback. 将该代码放在回调中。

Fixing your code, it should look like this: 修复你的代码,它应该是这样的:

function callDatabase(id) {
    var result;
    var connection = mysql.createConnection(
        {
            host        :   '192.168.1.14',
            user        :   'root',
            password    :   '',
            database    :   'test'
        }
    );

    connection.connect();
    var queryString = 'SELECT name FROM test WHERE id = 1';

    connection.query(queryString, function(err, rows, fields) {
        if (err) throw err;

        for (var i in rows) {
            result = rows[i].name;
        }

        connection.end();
        return result;
    });
}

Although, this will only solve part of the problem, since now you're still calling response.end(callDatabase(id)); 虽然,这只会解决部分问题,因为现在你还在调用response.end(callDatabase(id)); before waiting for a response from the query. 在等待查询的响应之前。

In order to fix this, you need to return some kind of callback. 为了解决这个问题,你需要返回某种回调。

function callDatabase(id, callback) {
    // the method code here...
    connection.query(queryString, function(err, rows, fields) {
        // code...

        // instead of returning the result, invoke the callback!
        callback(rows);
    });
}

Now you can call it like this : 现在你可以像这样调用它:

request.on('data', function (chunk) {
    var json = JSON.parse(chunk);
    var id = parseInt(json["id"]);
    callDatabase(id, function(res) {
        response.end(res);
    });
});

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

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