variable empty when doing an asynchronous call in node.js (closure)

Update: Solved, it was indeed a scope issue. I got around it by moving the user list code inside the database class and returning the prebuilt list.

Using node.js, I make an asynchronous call to function findUser and I build a list of users from the callback into the variable content. This works fine during the loop (where it says content variable is available) but when the loop exits, the variable is empty. How can I rewrite the code so that the value of variable content is available outside the loop?

exports.listUsers=function(req,res) {
    var content=''
    isLoggedIn=user.findUser({},function(myuser) {
        content =  content +'<li>' + myuser.firstname + ' ' + myuser.lastname + "</li>\n";
           //here value of content var is available
           console.log(content)
    })
        //here value of content var is empty
    console.log(content)
    showPage(req,res,{'content':content})
}

If findUser() is asynchronous (which you indicate), then the issue is that findUser() has not yet completed when showPage() is called.

For asynchronous functions, you can only use their results from the success handler function. You can't call an asynchronous function and expect to use it synchronously like your current code.

I don't know exactly what you're trying to accomplish, but this is the general design pattern you would need to use:

exports.listUsers=function(req,res) {
    isLoggedIn=user.findUser({},function(myuser) {
         var content = '<li>' + myuser.firstname + ' ' + myuser.lastname + "</li>\n";
         //here value of content var is available
         console.log(content)
         showPage(req,res,{'content':content})
    });
}

Or, if the callback is being called many times once for each user, you can accumulate the content and call showPage() on the last callback:

exports.listUsers=function(req,res) {
    var content = "";
    isLoggedIn=user.findUser({},function(myuser) {
         content += '<li>' + myuser.firstname + ' ' + myuser.lastname + "</li>\n";
         //here value of content var is available
         console.log(content)
         // devise some logic to know when the last callback is being called
         // perhaps based on a user count
         if (this is the last user callback) {
             showPage(req,res,{'content':content})
         }
    });
}