在回调函数内执行时,节点res.send()无法正常工作?

时间:2015-02-02 09:40:28

标签: javascript node.js asynchronous express callback

现在尝试各种技术并不占上风,任何人都可以对此有所了解。

//Google search -------------------
app.get("/google/:name", function (req, res) {
var term = req.params.name;

var searchTerm = function (search, callback) {
    var options = {
        hostname: "ajax.googleapis.com",
        path: "/ajax/services/search/web?v=1.0&q="+ search + ""
    };

    var gsaReq = http.get(options, function (response) {

        var completeResponse = '';

        response.on('data', function (chunk) {
            completeResponse += chunk;
        });

        response.on('end', function() {
            outputResult(completeResponse);
        });

    }).on('error', function (e) {

        console.log('problem with request: ' + e.message);

    });
}(term, outputResult);

function outputResult(result){

    console.log(result);

    res.send(result);
    // res.send('hello world');
};

});

如果res.send()发送hello world而不是我的回拨的result,尽管结果是字符串,这可以正常工作吗?有什么想法吗?

如果上述内容没有意义,则下面的代码会被简化(没有回调)且res.send()仍然会失败..?

如果没有回调,res.send就无法工作 - 啊哈:



app.get("/google/:name", function (req, res) {

    var term = req.params.name;

    var searchTerm = function (search) {
        var options = {
            hostname: "ajax.googleapis.com",
            path: "/ajax/services/search/web?v=1.0&q="+ search + ""
        };

        var gsaReq = http.get(options, function (response) {

            var completeResponse = '';

            response.on('data', function (chunk) {
                completeResponse += chunk;
            });

            response.on('end', function() {
                res.send(completeResponse);
            });

        }).on('error', function (e) {

            console.log('problem with request: ' + e.message);

        });
    }(term);


});




0 个答案:

没有答案