Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8789891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T22:31:28+00:00 2026-06-13T22:31:28+00:00

given the async nature of mongoose (or sequelize, or redis) queries, what do you

  • 0

given the async nature of mongoose (or sequelize, or redis) queries, what do you do when you have multiple queries you need to make before rendering the view?

For instance, you have a user_id in a session, and want to retrieve some info about that particular user via findOne. But you also want to display a list of recently logged in users.

exports.index = function (req, res) {
    var current_user = null

    Player.find({last_logged_in : today()}).exec(function(err, players) {
        if (err) return res.render('500');

        if (req.session.user_id) {
            Player.findOne({_id : req.session.user_id}).exec(function(err, player) {
                if (err) return;
                if (player) {
                    current_user = player
                }
            })
        }

        // here, current_user isn't populated until the callback fires 
        res.render('game/index', { title: 'Battle!',
                   players: players,
                   game_is_full: (players.length >= 6),
                   current_user: current_user
        });
    });
};

So res.render is in the first query callback, fine. But what about waiting on the response from findOne to see if we know this user? It is only called conditionally, so I can’t put render inside the inner callback, unless I duplicate it for either condition. Not pretty.

I can think of some workarounds –

  • make it really async and use AJAX on the client side to get the current user’s profile. But this seems like more work than it’s worth.

  • use Q and promises to wait on the resolution of the findOne query before rendering. But in a way, this would be like forcing blocking to make the response wait on my operation. Doesn’t seem right.

  • use a middleware function to get the current user info. This seems cleaner, makes the query reusable. However I’m not sure how to go about it or if it would still manifest the same problem.

Of course, in a more extreme case, if you have a dozen queries to make, things might get ugly. So, what is the usual pattern given this type of requirement?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T22:31:28+00:00Added an answer on June 13, 2026 at 10:31 pm

    Yep, this is a particularly annoying case in async code. What you can do is to put the code you’d have to duplicate into a local function to keep it DRY:

    exports.index = function (req, res) {
        var current_user = null
    
        Player.find({last_logged_in : today()}).exec(function(err, players) {
            if (err) return res.render('500');
    
            function render() {
                res.render('game/index', { title: 'Battle!',
                           players: players,
                           game_is_full: (players.length >= 6),
                           current_user: current_user
                });
            }
    
            if (req.session.user_id) {
                Player.findOne({_id : req.session.user_id}).exec(function(err, player) {
                    if (err) return;
                    if (player) {
                        current_user = player
                    }
                    render();
                })
            } else {
                render();
            }
        });
    };
    

    However, looking at what you’re doing here, you’ll probably need to look up the current player information in multiple request handlers, so in that case you’re better off using middleware.

    Something like:

    exports.loadUser = function (req, res, next) {
        if (req.session.user_id) {
            Player.findOne({_id : req.session.user_id}).exec(function(err, player) {
                if (err) return;
                if (player) {
                    req.player = player
                }
                next();
            })
        } else {
            next();
        }
    }
    

    Then you’d configure your routes to call loadUser wherever you need req.player populated and the route handler can just pull the player details right from there.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given that the web application doesn't have su privileges, I'd like to execute a
My question involves async operations in VB .NET. Given the following: Delegate WorkerDelegate(Byval asyncOp
I understand the Async nature of Silverlight, but one thing that constantly hampers my
I have been wondering... Do the new Async constructs actually allow for intermediate results
I need to create a gate to a resource in an async programming model
On all my site pages I have the google analytics async code setup as
I have a WCF service(maybe multiple services) and a client in Silverlight(C#). As I
Do you need your property to be Atomic, when using multiple threads and only
I have a Async Task that does not add the percentage while it is
Given the following XML: <?xml version=1.0?> <soap:Envelope xmlns:soap=http://www.w3.org/2003/05/soap-envelope xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema> <soap:Body> <GetMsisdnResponse xmlns=http://my.domain.com/> <GetMsisdnResult>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.