无法从回调函数内部访问响应

时间:2013-12-04 23:13:06

标签: javascript node.js

我在回调函数中完成响应时遇到问题。如果表存在,则以下精简代码应检查mysql连接查询内部并使用此信息完成响应。但事实并非如此。当我在查询中访问结果时,它似乎是另一个变量,并且其中的result.end()不会结束响应。不应该导致相同的范围并能够完成我的回复?我怎样才能实现目标?

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    mysql = require('mysql'),
    fs = require('fs'),
    connection = mysql.createConnection({
        host: 'localhost',
        user: 'foo',
        passwort: 'bar'
    });

connection.connect(function (err) {
    if (err)
        throw err;
});

http.createServer(function (request, result) {

    // some request handling

    if (request.url == '/index' && request.method.toLowerCase() == 'get') {
        result.writeHead(200, {
            "Content-Type": "text/plain",
            "Access-Control-Allow-Origin": "*"
        });
        result.write('Response:\n\n');

        // result.end(); <- At this position it would create the expected response.

        connection.query('USE Database', function (err, results) {
            if (err)
                throw err;
            connection.query('SHOW TABLES LIKE "Table"', function(err, results) {
                if (results.length == 0)
                    result.write('table not found');
                result.end(); // <- this one don't
            });
        });
    }
}).listen(8080);

1 个答案:

答案 0 :(得分:0)

我会将您的代码重写为以下内容:

var http = require('http'),
    mysql = require('mysql'),
    connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root'
    });

connection.connect(function (err) {
    if (err) {
        throw err;
    }

    console.log('Connected!');
});

http.createServer(function(req, res) {
    connection.query('USE test', function (err, results) {
        if (err) {
            res.end("ERROR from 'USE test'");
        } else {
            connection.query('SHOW TABLES LIKE "Table"', function(err, results) {
                if (results.length == 0) {
                    res.end('table not found');
                } else {
                    res.end('table found!');
                }
            });
        }
    });
}).listen(8080);