javascript - Express session inside callback comes back undefined outside -


i have route written in express following:

app.get("/route", function(req, res){     if (someboolean){         somefunction(stuff, function(user){             ...             req.session.user = user;         });      }     res.render("route"); } 

when someboolean true, session should set. however, after moving on different page, req.session.user comes undefined. checking req.session.user inside somefunction comes defined however. solution have found session becoming undefined outside scope of somefunction move res.render("route") somefunction such:

app.get("/route", function(req, res){     if (someboolean){         somefunction(stuff, function(user){             ...             req.session.user = user;             res.render("route");         });      } } 

this causes route fail when someboolean false. i'm thinking caused asynchronous nature of node.js, not sure. causing occur exactly, , proper solution?

simplest solution be:

app.get("/route", function(req, res){     if (someboolean){         somefunction(stuff, function(user){             ...             req.session.user = user;             res.render("route");         });      }else{         res.render("route");     } } 

using promises can ( first promisify somefunction):

app.get("/route", function(req, res){     promise.resolve()       .then(function(){           if(someboolean){             return somefunction(stuff)               .then(function(user){                 res.session.user = user;               });           }       }).then(function(){         res.render("route");       }); } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -