开发者

Delaying events until a callback is called (Node.js)

I am using Node.js with Express and have code similar to this as part of my routes:

requireLogin: function(req, res, next) {
    User.find(req.session.userId)
        .on('success', function(user) {
             req.addListener('data', function(chunk) {
                 console.log("DATA: " + chunk);
             }
             next()
        }
}

I am using Sequelize and the User.find method is accessing the database. The trouble is, the request 'data' event that I bind to is never fired. It seems that the data event had already been triggered and handled by the time the user is returned from the database and it's too late to do anything with it. In the example above I could just move the req开发者_如何转开发.addListener to outside the database callback, but in reality I am calling next() here which can't be moved.

All of the following route middleware that is called by next() then doesn't have access to the request data since these events have already been fired. Worse than that, they just hang waiting for the data event from req because it has already happened.

How can I somehow delay the data event so that it can be bound to from within the database callback? Or have I misunderstood something fundamental and need to change my way of going about this?

Thanks a lot.

Edit: I found a relevant discussion in the nodejs Google group which suggests there isn't a solution that will work for me.


var cache = new function () {
    var arr = [],
        cbs = [];

    this.add = function(data) {
        arr.push(data);
        cbs.forEach(function(cb) {
            cb(arr);
        });
    }

    this.get = function(cb) {
        cbs.push(arr);
        if (arr.length > 0) {
            cb(arr);
        }
    }
};

req.addListener('data', function(chunk) {
    cache.add(chunk);
};

User.find(
    req.session.userId
).on('success', function(user) {
    cache.get(function(data) {
        // stuff
        next();
    });

};

I presume what you actually want is some kind of message caching. Now this is a vague proof of concept. What you actually want depends on your code.

If you have any kind of deferred library / abstraction available then the code will become a lot smaller.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜