kand
kand

Reputation: 2338

Node.js Express and Mongoose, rendering after a save()

I just started experimenting with Node.js Express and Mongoose by creating a simple blog website.

I am trying to build some routes that will do some simple db operations, but I'm getting confused with asynchronous functions and if my code will execute properly every time.

This is basically what I have:

app.get('/createUser', function(req, resp) {
    var newUser = new User({name: 'abc123', pass: 'password321'});
    newUser.save(function(err){ // will this callback always be called correctly?
        if(err) resp.send('ERROR!');
        resp.send('SUCCESS!');
    });
});

So I want the response to be written out as "ERROR!" for any error in saving, and "SUCCESS!" when the save was successful. However, I'm confused about the timing of these functions. Will the get() function ever return before the save() is completed? And if so, will the response not be written out properly?

Upvotes: 2

Views: 2592

Answers (1)

Hector Correa
Hector Correa

Reputation: 26700

The get() function will complete before the save function does, but since there is nothing writing a response until the save callback is executed then the response won't be available to the browser until then.

I added a few console.log() calls to your code so you can see the order of execution:

app.get('/createUser', function(req, resp) {

    console.log('this will print first');

    var newUser = new User({name: 'abc123', pass: 'password321'});
    newUser.save(function(err){ // will this callback always be called correctly?

        console.log('this will print last');

        if(err) {
            resp.send('ERROR!');
        }
        else {
            resp.send('SUCCESS!');
        }
    });

    console.log('this will print second');

});

Upvotes: 4

Related Questions