最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS Asynchronous Database Calls - Stack Overflow

programmeradmin3浏览0评论

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:

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', 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.

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

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:

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', 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.

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

Share Improve this question asked May 3, 2015 at 12:27 Nicholas MordecaiNicholas Mordecai 9092 gold badges13 silver badges35 bronze badges 2
  • You can't return from an asynchronous function, you'd have to use a callback and then place response.end inside that callback etc. – adeneo Commented May 3, 2015 at 12:29
  • Is there somewhere online where I can see an example of using a callback and returning a value to it? – Nicholas Mordecai Commented May 3, 2015 at 12:40
Add a ment  | 

1 Answer 1

Reset to default 7

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

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);
    });
});
发布评论

评论列表(0)

  1. 暂无评论