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(, 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.

Problem courtesy of: dzm


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 callbacksQuite annoying actually but sometimes necessary (if for example the second call depends on the first call);

  • Asynchronous callbacks queueIn 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

Solution courtesy of: freakish

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Expressjs/node.js equivalent to exit() in php

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录