uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

async_demo #32

Open uniquejava opened 8 years ago

uniquejava commented 8 years ago

https://github.com/alsotang/async_demo

uniquejava commented 8 years ago

cyper's code

Room.find({'members.userid': me}, function (err, rooms) {

    var funcs = [];
    _.each(rooms, function (room) {
        var roomId = room.room;
        console.log('====== each ' + roomId);

        var meObj = _.findWhere(room.members, {userid: me});
        var lastRead = meObj.last_read;

        room = _.pick(room, 'room', 'name');

        funcs.push(_.partial(calcUnread, room, lastRead));
    });

    async.parallel(funcs, function (err, results) {

        res.json({groups: results, msgs: msgs});
    });

});
function calcUnread(room, lastRead, cb) {
    var unread_cnt = 0;

    var q = Message.aggregate([
        {$match: {room: room.room, crt_time: {$gt: lastRead}}},
        {
            $group: {
                _id: null,
                count: {$sum: 1}
            }
        }
    ]);

    q.exec(function (err, result) {
        if (err) {
            console.error(err);
        }
        if (result.length > 0) {
            unread_cnt = result[0].count;
        }

        console.log('unread_cnt is ' + unread_cnt);
        room['unread_cnt'] = unread_cnt;

        cb(null, room);

    });

}