4

I'm using the opentok SDK for video chatting, and I need to create sessions. It's pretty straightforward, and that part's working fine. This is all being done in node.js, server side.

The issues is - and it's mostly cause I still don't quite get var scopes (especially with anonymous functions and closures) - I have a value inside of my anonymous function that I want to access (preferably by assigning it to another var, one that's in its parent scope), but can't!

Something like this:

function generateSession(session){
  var session='';
   opentok.createSession(function(error, sessionId){
      if (error) {
        throw new Error("Session creation failed.");
      }
      session = sessionId;
   });
   return session;
}

session retains it's initial value of '' (empty string), not the sessionId it was assigned to. Help?

cintron
  • 513
  • 5
  • 19

2 Answers2

4

This isn't a question about scope. It's about asynchronicity. Your anonymous function will update the session variable in the parent function; but because your anonymous function is asynchronous, it'll happen after generateSession has returned.

Instead, you'll need to modify generateSession to accept a callback, and execute the callback (passing the generated session), once it's completed;

function generateSession(session, cb){
   opentok.createSession(function(error, sessionId){
      if (error) {
        throw new Error("Session creation failed.");
      }

      cb(sessionId);
   });
}

generateSession(blahblahblah, function (session) {
    // Access session here.
});

This is the exact same problem as for How do I return the response from an asynchronous call? (in that situation, it's the "success" callback that is asynchronous); there might be a more suitable duplicate, but I can't find one :(. It'll still be beneficial to read through it though.

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
1

createSession is an asynchronous function. Its callback is not executed until some time after generateSession has finished. You need to pass in a callback instead:

function generateSession(cb){
  opentok.createSession(cb);
}

generateSession(function(err, sessionId) {
  if (err) throw err;
  // use sessionId
});
mscdex
  • 104,356
  • 15
  • 192
  • 153