Pregunta

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?

¿Fue útil?

Solución

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);
        });
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top