0

So I've got a function that calls a callback. It is inside another function

function otherFunction() {

    getUserStatus(function(status) {
        console.log(status);
    });
}

The function getUserStatus() does all the processing I want, and console.log() displays the correct variable.

However I can't seem to access the variable outside the scope of the callback function. I want to access it in otherFunction()

I tried creating a variable outside of the callback function (inside of otherFunction()) by using var status; and var otherstatus; and assigning status to these variables, but assigning them to what I would think would be a variable in scope didn't work either.

So how do I get this variable into the scope of the function?

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • The linked question title is specific to Ajax calls, but at its core it is the same question, and the answers are applicable, since the problem comes from the A of Ajax (Asynchronous), and that is what you are experiencing too. I hope the answers there help you. – Paul Feb 14 '15 at 19:03
  • But this isn't my async function, I'm trying to get the response once the async function has been called. getUserStatus is the aync function. – Steven Matthews Feb 14 '15 at 19:10
  • I don't think you understand my question. According to what you're saying, there is never a way to get an async result back into standard program flow. – Steven Matthews Feb 14 '15 at 19:13
  • That is correct, there is no way. That standard program flow executes before your callback does, and before `status` has got any value. – Paul Feb 14 '15 at 19:17
  • Promises are a very elegant way to solve this though and maintain nice code structure. I recommend you read about Promises, as they'll solve this problem and make your life easier whenever you work with asynchronous code in the future. The bluebird promise library is especially good about how it allows you to deal with exception handling: https://github.com/petkaantonov/bluebird – Paul Feb 14 '15 at 19:18

0 Answers0