Search code examples
javascriptnode.jsasynchronousnode-async

Sync http request in Node


I'm new to node and I'm trying to figure out the callbacks and the async nature of it.
I have this kind of function:

myObj.exampleMethod = function(req, query, profile, next) {
    // sequential instructions
    var greetings = "hello";
    var profile = {};

    var options = {
        headers: {
            'Content-Type': 'application/json',
        },
        host: 'api.github.com',
        path: '/user/profile'
        json: true
    };

    // async block
    https.get(options, function(res) {

        res.on('data', function(d) {
            // just an example
            profile.emails = [
                {value: d[0].email }
            ];
        });

    }).on('error', function(e) {
        console.error(e);
    });

    //sync operations that needs the result of the https call above
    profile['who'] = "that's me"

    // I should't save the profile until the async block is done
    save(profile);

}

I was also trying to understand how to work with the Async library given that most of the node developers use this or a similar solution.

How can I "block" (or wait for the result) the flow of my script until I get the result from the http request? Possibly using the async library as an example

Thanks


Solution

  • Based on the fact that you're trying to "block" your script execution, I don't think you have a firm grasp on how async works. You should definitely read the dupe I suggested, especially this response:

    How do I return the response from an asynchronous call?

    To answer your question more specifically:

    async.waterfall([
        function(callback) {
            // async block
            https.get(options, function(res) {
    
                res.on('data', function(d) {
                    // just an example
                    profile.emails = [
                        {value: d[0].email }
                    ];
                    callback(null);
                });
    
            }).on('error', function(e) {
                throw e;
            });
        },
        function(callback) {
            // I should't save the profile until the async block is done
            save(profile);
            callback(null);
        }
    ]);