문제

I want to setup a restify node.js server using the following code:

server.get('/querySomething', function(req, res) {
   var toReturn = getSomethingElse(req.params);
   res = toReturn;
]);

...

var getSomethingElse = function(params) {
    var somethingElse;        
    var opts = {
    host: "some.host.com",
        path: "/x",
        method: "GET"
    }
    var req = https.request(opts, function(res) {
        res.on('data', function(someResult) {
       somethingElse = someResult;
        });
    });

    return somethingElse;
};

I understand that the "https.request" call gets executed asynchronously.

So how can I "wait" for the call to return before returing its result as response to the "/querySomethingElse" http request?

도움이 되었습니까?

해결책

I mentioned you have 'toReturn' stuff in there which is wrong, you do not ever return anything when working with async code you call events when you finished.

One way of doing it using express is something in the lines of:

server.get('/querySomethingElse', function(request, response) {

    var opts = {
        host: "some.host.com",
        path: "/x",
        method: "GET"
    }

    var req = https.request(opts, function(res) {
        res.on('data', function(someResult) {
            response.send(someResult);
        });
    });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top