简体   繁体   中英

Is it possible to call a function from another function, using an external variable?

I've created a function that creates a session ID

sessionId = ot.create_session(location, function(sessionId){
    console.log('The session ID is: ' + sessionId + '++++++++');
    return sessionId;
});

I can print out the session ID from within the function, but can't access it from outside of the function.


Failing that, I wanted to call a function, passing the variable to the function

sessionId = ot.create_session(location, function(sessionId){
    console.log('The session ID is: ' + sessionId + '++++++++');
    sendToUser(sessionId);
});

However, I need sendToUser to have more data, a previously declared variable called data

So..I would then do

sessionId = ot.create_session(location, function(sessionId){
    console.log('The session ID is: ' + sessionId + '++++++++');
    sendToUser(sessionId);
});

sendTo User(sessionId, data){
}

However, this doesn't work, either

The entire code is at : http://pastebin.com/CdV3rdh0

The following snippet:

setTimeout(function() {
   console.log("I'm first! Am I?"); // #2
}, 0);

console.log("Hahah, I'm first!"); // #1

would log at first "Hahah, I'm first!" and then "I'm first! Am I?" to the console. Why?

The javascript interpreter runs any function from top to bottom first, before it is doing anything else (like executing the callback function after zero seconds). This is because functions in javascript are normally non-blocking and IO is done asynchronously. That means, setTimeout is not waiting until the anonymous function it's got as first argument got executed, but only registers the function callback to be executed in zero seconds. It gets executed right after the interpreter reached the end of the file.

Because ot.create_session needs to write a file to disk to create the session, the sessionId is only available inside of the callback function, and you will never get the sessionId out of there, because when the callback function gets called, the outer function has already finished executing and the whole context is already gone :)

Why do you need the session id from the outside of the callback function anyway? The second parameter data for sendToUser seems to be available inside the callback function, too. Simply write sendToUser(sessionId, data) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM