节点JS异步数据库调用 [英] Node JS Asynchronous Database Calls

查看:96
本文介绍了节点JS异步数据库调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管数据库函数未返回值,但我在使节点无法继续进行数据库调用时遇到问题.

I am having issues getting node to make a database call without proceeding despite the database function has not returned a value.

这是基本的http服务器代码:

Here is the basic http server code:

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

使用request.on('data')函数,我可以从请求中解码JSON并继续进行数据库调用:

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', function (chunk) {
    var json = JSON.parse(chunk);
    var id = parseInt(json["id"]);
    response.end(callDatabase(id));
});

数据库功能如下:

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

但是在测试中,这证明我做错了.我知道我可能想使用节点异步模块,这一点我已经很累了.我也尝试过使用Waterfall方法,以及在线并行和许多其他教程.我觉得request.on函数应该是并行的,然后数据库调用async,所以当节点等待数据库服务器的响应时,它可以自由地继续处理任何其他请求,从而将排队时间减至最少.

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.

如果我对Node js的任何概念有误解,请告知我.

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

推荐答案

您将返回result并在查询从数据库返回其值之前关闭连接.将该代码放入回调中.

You are returning result and closing the connection before the query has returned it's value from the db. 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;
    });
}

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

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.

为解决此问题,您需要返回某种回调.

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

这篇关于节点JS异步数据库调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆