Home:ALL Converter>Javascript function returning session object

Javascript function returning session object

Ask Time:2012-02-24T06:00:56         Author:user1113883

Json Formatter

This is a simple script to retrieve a 'CouchDB' session and get the user information. It utilizes 'couch.j's which uses 'jQuery'. I've been using JavaScript for a little while but I can't figure out how to pass return values and then use them.

$(document).ready(function () {
  this.ctx = getCtx(); //it doesn’t appear that this is actually assigning a variable
  console.log(this.ctx);   //this returns “undefined”
});

function getCtx(){

     $.couch.session({
        async: false,
        success: function(r) {

              ctx = r.userCtx;
              if (ctx != null){ //I added this check because otherwise ctx was returning undefined.

                    console.log("returning ctx: "+ctx);   
//Log says: returning ctx: [object Object]
                    return ctx;                           
//I know this is returning an object, because of the line above

              }
        }
  });
};

What is stumping me even more is that the console.log statement in the $(document).ready function is returning "undefined" before the console.log statement in the getCtx() function returns. Which means that it isn't giving getCtx() time to execute and actually get the session.

Author:user1113883,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/9422052/javascript-function-returning-session-object
yy