Question

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?

Was it helpful?

Solution

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);
        });
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top