Search code examples
javascriptnode.jsopentok

Variable in parent scope not getting altered in anonymous function


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?


Solution

  • 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.