简体   繁体   English

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

[英]Can't access a response from inside a callback function

I have a problem finishing a response from within a callback function. 我在从回调函数中完成响应时遇到问题。 The following pared-down code is supposed to check inside a mysql connection query if a table exists and finish the response with this information. 下面的精简代码应该在mysql连接查询中检查是否存在表,并使用此信息完成响应。 But it doesn't. 但事实并非如此。 When I access result within the query it seems to be another variable and the result.end() inside it doesn't end the response. 当我在查询中访问结果时,它似乎是另一个变量,并且其中的result.end()不会结束响应。 Shouldn't be result in the same scope and able to finish my response? 不应在相同的范围内得出结论并能够完成我的回答吗? How can I achieve my goal? 我如何实现我的目标?

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

I would rewrite your code to the following: 我会将您的代码重写为以下内容:

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

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

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