javascript - variable empty when doing an asynchronous call in node.js (closure) -
update: solved, indeed scope issue. got around moving user list code inside database class , returning prebuilt list.
using node.js, make asynchronous call function finduser , build list of users callback variable content. works fine during loop (where says content variable available) when loop exits, variable empty. how can rewrite code value of variable content available outside 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 available console.log(content) }) //here value of content var empty console.log(content) showpage(req,res,{'content':content}) }
if finduser()
asynchronous (which indicate), issue finduser()
has not yet completed when showpage()
called.
for asynchronous functions, can use results success handler function. can't call asynchronous function , expect use synchronously current code.
i don't know you're trying accomplish, general design pattern need 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 available console.log(content) showpage(req,res,{'content':content}) }); }
or, if callback being called many times once each user, can accumulate content , call showpage()
on 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 available console.log(content) // devise logic know when last callback being called // perhaps based on user count if (this last user callback) { showpage(req,res,{'content':content}) } }); }
Comments
Post a Comment