Search code examples
node.jssessionpromiseuser-management

session is undefined outside the async method in node js


Guys I am newbie in nodejs. My requirement is to save few user details from different tables for further process in my rest api project, after reading I got that I should save result from queries in session for further use. Here is my code ,I am not able to get session values outside the query result async call. What is the best way to save user details from different tables and use them for further queries.

method:

 if(sess.email)
      {
        console.log("session is valid");
          checkProfile.getRightOnCity(req.decoded , req.session);
          console.log("city session ::" ,  sess.cities); //i am getting this undeifned
      }

getRightOnCity:

var getRightOnCity = function getRightOnCity(req_decoded,req_session) {
    var myPromise = dbname(req_decoded);
    var user_id = getUserid(req_decoded);
    var details = getUserDetails(req_decoded);

    console.log("user details :: " , details);
    var cities = [];
    myPromise.then(function(myDBName) { 

        new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id="+user_id, function (err, res) {
        if(err) {
                    console.log("error: ", err);
                    result(null, err);
                }
                else{

                for(var i=0 ; i < res.length ; i++) {
                  cities.push(res[i].city_id);
                  req_session.cities = cities.join();

                  console.log("city::" , req_session.cities);
                  console.log("email inside get cities " ,  req_session.email);
                  req_session.save();

                }  


              }
            }); 

    });  

};

Solution

  • First you need to RETURN the promise from the getRightOnCity function.

    return myPromise.then and may need to wrap the DB call in promise as well.

    function getRightOnCity(req_decoded, req_session) {
        var myPromise = dbname(req_decoded);
        var user_id = getUserid(req_decoded);
        var details = getUserDetails(req_decoded);
    
        console.log("user details :: ", details);
        var cities = [];
        return myPromise
            .then(function (myDBName) {
                return new Promise((resolve, rej)=>{ //<==here
                    new_conn(myDBName).query("Select city_id from " + myDBName + ".rights_on_city where user_id=" + user_id, function (err, res) {
                        if (err) {
                            console.log("error: ", err);
                            result(null, err);
                            rej(err);
                        } else {
                            for (var i = 0; i < res.length; i++) {
                                cities.push(res[i].city_id);
                                req_session.cities = cities.join();
    
                                console.log("city::", req_session.cities);
                                console.log("email inside get cities ", req_session.email);
                                req_session.save();
                            }
                            resolve();
                        }
                    });
                })
            });
    
    };
    

    Now, to use it you need .then or await the function.

    if (sess.email) {
        console.log("session is valid");
        checkProfile
        .getRightOnCity(req.decoded, req.session)
        .then(()=>{
            console.log("city session ::", sess.cities);
        })
    }
    

    Note: It is not a good idea to mix Promise and callback