1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@freekish I went ahead and did the nested callbacks - but that Async library is sweet! I'll have to switch it over - thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.