-1

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

Leonardo
  • 4,046
  • 5
  • 44
  • 85
  • No, I don't think so. My scope is in node and I'd like to see an example usage of the async library for this use case – Leonardo May 07 '15 at 17:47
  • 2
    "block[ing]" the javascript until the result is back goes completely against writing asynchronous code. you need to instead run the code that you wanted to run after the async action inside the async action's callback function. that's the whole point of the callback function being there. The linked duplicate explains that pretty well. (and the answer below covers your specific usecase, though you don't really need the async library for this.) – Kevin B May 07 '15 at 18:05

1 Answers1

1

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);
    }
]);
Community
  • 1
  • 1
Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50