Expressjs/node.js equivalent to exit() in php

I'm using Expressjs w/ node.js and I have a route like this:

    users.init(app.db, function() {

        users.checkUsername(user.username, function(err, count) {
            if (count > 0) {
                res.json({'username': 'unavailable'});
            }
        });

        users.checkEmail(user.email, function(err, count) {
            if (count > 0) {
                res.json({'email': 'unavailable'});
            }
        });

        users.insertUser(user, function(err, response) {
            res.json({'success' : 'true'});
        });

    })  

This will print send multiple responses, username and email for example, in some cases.

This route is being called via ajax, in php, I normally do an exit() after I echo out a json response. Is there a way to do that in Expressjs?

Thank you!

EDIT: I could wrap everything in if/else or set a flag inside each, but just seeing if there's a more elegent way.

You can't do "multiple responses" (whatever that means) with res.json - every time you use it, it sends the data to the client and finalizes the response. You need to hold (and update) the result in a variable and send it at the very end.

Now I can think of 2 possibilities for you:

  • Nested callbacks Quite annoying actually but sometimes necessary (if for example the second call depends on the first call);

  • Asynchronous callbacks queue In callbacks check if every other callback finished the job. If so do the response. This may be a bit tricky to implement it yourself, so try for example an excelent async library.