Variable Scope from Callback

I’m running this code server-side:

    var sessionId;

    //Generate a basic session. Or you could use an existing session ID.
    opentok.createSession({mediaMode:'routed', archiveMode:'always'}, function(error, session) {
      if (error) {
        throw new Meteor.Error(500, error.message);
      } else {
        sessionId = session.sessionId;
        console.log('Created session',sessionId);
        return session.sessionId;
      }
    });

    console.log(sessionId);

And the createSession method is running successfully. I’m getting the ‘Created session’ and a session id, but I can’t figure out how to access sessionId outside that callback function. The following console.log(sessionId) returns undefined, and it seems to return it before createSession runs. So what’s the smart move here? This is a collection. It’s impossible to get the sessionId at this point.

Yep - welcome to asynchronous programming with Javascript :slight_smile:

There are two ways to address this: Meteor.wrapAsync or Promises (with or without async/await).

Meteor.wrapAsync

const opentokCreateSession = Meteor.wrapAsync(opentok.createSession, opentok);

//Generate a basic session. Or you could use an existing session ID.
try {
  const session = opentokCreateSession({ mediaMode: 'routed', archiveMode: 'always' });
  const sessionId = session.sessionId;
  console.log('Created session', sessionId);
  return sessionId;
} catch (error) {
    throw new Meteor.Error(500, error.message);
}

Promises and async/await

If your code is in a Meteor method, you should check out Using Promises and async/await in Meteor.