nwkeeley
nwkeeley

Reputation: 1437

Struggling with node.js concept on sync vs async

I come from a PHP background and have started using node.js. Most things I am doing okay on but there are some thing thats I am having a hard time wrapping my head around when it comes to sync vs async and scope.

Here is a pretty simple example:

app.get('/register/:invite_id?' function(req, res) {
    var agent = superagent.agent(); 
    var form = {};

    agent.post('127.0.0.1/invite/' + req.params.invite_id + '/details')
         .end(function(invite_error, invite_details) {
             form.email = invite_details.body.user.email;
             //I can console.log form.email here
         });


    // I cannot console.log form.email here.. i get undefined.
    // I need to access form.email here, so I can pre-populate my form field below...
    // Sometimes however that agent.post may take 2-3 seconds


    res.render('user/register', {
        form: form
    });

});

Upvotes: 0

Views: 427

Answers (1)

Golo Roden
Golo Roden

Reputation: 150624

You have to move your call to the render function to the line with the comment in the callback function of your post:

app.get('/register/:invite_id?' function(req, res) {
    var agent = superagent.agent(); 
    var form = {};

    agent.post('127.0.0.1/invite/' + req.params.invite_id + '/details')
         .end(function(invite_error, invite_details) {
             form.email = invite_details.body.user.email;
             res.render('user/register', {
                  form: form
             });
         });
});

That way the form variable is accessible and can be rendered to the response stream.

Generally speaking, I'd also recommend to you to make yourself familiar with the concept of closures (which are, to put it simple, functions that are passed around, either as parameters or as return values).

Note: I KNOW that a closure is something slightly different than what I wrote above, but I think that for a beginner this is much easier to grasp than the bullet-proof explanation.

For an introduction to closures, you may start at What is a 'Closure'?

Upvotes: 1

Related Questions