Variable in parent scope does not change in anonymous function

I am using the opentok SDK for video chat and I need to create sessions. This is pretty simple, and this part is working fine. All this is done in node.js, on the server side.

Problems - and this basically leads to the fact that I'm still not quite getting var scopes (especially with anonymous functions and closing). I have a value inside my anonymous function that I want to access (preferably by assigning it to another var, one that is in its parent area), but cannot!

Something like that:

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

sessionsaves the original value '' (empty string), and not sessionIdto which it was assigned. Help?

+4
2

. . session ; , , generateSession .

generateSession, , ( session) ;

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.
});

, ? ( "" , ); , , :( , .

+4

createSession - . generateSession. :

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

generateSession(function(err, sessionId) {
  if (err) throw err;
  // use sessionId
});
+1

Source: https://habr.com/ru/post/1542349/


All Articles