处理异步http调用节点js

时间:2015-11-06 05:27:07

标签: node.js http asynchronous

我在节点js服务器上有一个RESTish api。当它收到GET请求时,它将调用一个函数,然后调用另一个服务器获取函数。代码如下所示:

var server = http.createServer(function(request, response) {
    console.log("YEAHHH! ", request.method);
    var string='';
    // Inside a request handler method
    if (request.method == "OPTIONS") {
        console.log("options");
        // Add headers to response and send
        //response.writeHead(statusCode, responseHeaders);
        response.writeHead(success,responseHeaders);
        response.end();
    }
    if(request.method == "GET") {
        string = soso();
    }

    console.log("*******", string);
    response.writeHead(success,responseHeaders);
    response.end(string);
});

soso()是对其他服务器的调用。问题是我想在完成之前发送soso()函数的响应,所以我得到的是一个空字符串。

我该如何解决这个问题?

我确定这是重复但却无法找到我正在寻找的东西。所以,任何帮助表示赞赏。

修改

soso功能代码:

var soso = function () {
    console.log("this is being called");
    var options = {...}

    var req = https.get( options, function(res)  {
        var str = '';
        res.on('data', function ( chunk ) {
            str += chunk;
        })

        res.on('end', function () {
            console.log ( "str is: ", str );
            string = str;
        })

        req.end();
        console.log(res.statusCode);
        console.log(responseHeaders);
    });

}

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情,我不确定。我没有测试过这个。在soso函数中传递响应对象,然后在get请求结束后使用$response = new RedirectResponse("someUri", Codes::HTTP_FORBIDDEN); $event->setResponse($response);

response.end(string);

soso功能

var server = http.createServer(function(request, response) {
        console.log("YEAHHH! ", request.method);
        var string='';
        // Inside a request handler method
        if (request.method == "OPTIONS") {
            console.log("options");
            // Add headers to response and send
            //response.writeHead(statusCode, responseHeaders);
            response.writeHead(success,responseHeaders);
            response.end();
        }
        if(request.method == "GET") {
            string = soso(response);   //send response object as argument
        } else {
     console.log("*******", string);
        response.writeHead(success,responseHeaders);
        response.end(string);
    }


    });