javascript Node JS 异步数据库调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30013802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:30:15  来源:igfitidea点击:

Node JS Asynchronous Database Calls

javascriptmysqlnode.jsasynchronousparallel-processing

提问by Nicholas Mordecai

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,所以当节点在等待来自数据库服务器的响应时,它可以自由处理任何其他请求,将排队时间降到最低.

Please inform me if I have miss-understood any of the concepts of node js.

如果我对 node js 的任何概念有误解,请告诉我。

回答by gillyb

You are returning resultand closing the connection before the query has returned it's value from the db. Place that code inside the callback.

result在查询从数据库返回它的值之前,您正在返回并关闭连接。将该代码放在回调中。

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));before waiting for a response from the query.

虽然,这只能解决部分问题,因为现在您仍在response.end(callDatabase(id));等待查询响应之前调用。

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