Get HTTPS response outside of the current function

43 views
Skip to first unread message

Tiago Hillebrandt

unread,
Jan 6, 2015, 7:05:42 PM1/6/15
to nod...@googlegroups.com
Hey guys,

I need to do an HTTPS request to the Linode API.

That said, I am looking if would be possible to return an HTTPS response as value on this function: http://paste.ubuntu.com/9684987/

I tried some specific things to make the thread wait until request ends, like setTimeout() and while (!req.finished) {}, but nothing seems to work as expected.

This is my first Node.js implementation, so I am not sure if this would be the better way to perform this action.

Do you guys have any suggestions on this?

Thanks in advance!


Ryan Graham

unread,
Jan 6, 2015, 8:18:50 PM1/6/15
to nod...@googlegroups.com
The closest you could get to "returning the response" in this case is to return a Promise, but that's probably a whole other discussion (which I can't describe any better than Marc Harter did in http://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/ ).

Promises or not, however, you won't be able to get around the fact that the response will be asynchronous and your response handling code will be called "some time in the future".

~Ryan

zladuric

unread,
Jan 7, 2015, 2:22:19 AM1/7/15
to nod...@googlegroups.com
I assume you're trying to make a synchronous call from a node.js script, then when it finishes, do other things as well.

If your other scripts are also node.js, you would probably add a `callback` parameter to your _call method, and call it when done.

Example:

    function _call(cb) {
    
      request.get(someUrl, function(err, response) {
        // handle err if any 
        if(err) {return cb(err);}
    
        // do stuff with body, i.e. your JSON.parse
        // then call the callback
        cb(null, response.body);
      });
    });
    // then export the function
    module.exports.call = _call;

You would call this as follows, from other modules:

    var myModule = require('./linode-module.js');
    // when you call the module, pass it a function that will be executed when done. That is where you get the results.
    myModule.call(function(err, body) {
    
        // this function will receive your response.
        console.log(body);
        // now you can do other useful things with it.
    });


Hope that helps.

Zlatko
Reply all
Reply to author
Forward
0 new messages