Delaying events before calling a callback (Node.js)

I am using Node.js with Express and have code like 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 accesses the database. The problem is that the data event, which I am linking, never fires. It seems that the data event has already been triggered and processed by the time the user returns from the database, and it is too late to do anything with it. In the above example, I could just move req.addListener outside of the database callback, but in fact I call the following () here, which cannot be moved.

All of the following route middleware, which is called next (), then does not have access to the request data, since these events have already been triggered. Worse, they just wait for the data event from req, because it has already happened.

How can I somehow delay a data event so that it can be associated with a database callback? Or did I misunderstand something fundamental and do I need to change my way of doing this?

Many thanks.

Edit: I found a related discussion in the nodejs google group that says there is no solution that will work for me.

+3
source share
1 answer
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();
    });

};

, , - . . , , .

- /, .

0

All Articles