1

Sounds like a basic question, but I am stuck with the javascript variable scoping. I want to get a function value that was passed as an argument to another function.

Example: Global variable number1 always returns the initial value ' ' in stead of the value of the second argument of the get function.

What´s wrong?

    var number1 = '';
    cordova.require("applicationPreferences").get("NumTel",function (value) {
             number1 = value;
        },
        function (error) {}
    );
   console.log("Number1 = " + number1);

1 Answer 1

3

Because you have at least one asynchronous operation, you cannot get that value out of the function because that function will get called sometime in the future, long after your console.log() statement has already executed.

In asynchronous programming, you must use the value either inside the callback or you must call another function from the callback and pass it the value. To use asynchronous programming in javascript, you have to change your design thinking. You cannot just use synchronous techniques because the flow of code is no longer synchronous.

Move all your logic that wants to use that value into the callback itself.

cordova.require("applicationPreferences")
       .get("NumTel", function (value) {
            // put all your code here that uses value
            // or call another function and pass the value to it
            myFunc(value);
        }, function (error) {
        }
);

function myFunc(x) {
    console.log("Number1 = " + x);
}

Or, you could do it without even having the anonymous function like this:

cordova.require("applicationPreferences")
       .get("NumTel", myFunc, function (error) {
       }
);

function myFunc(x) {
    console.log("Number1 = " + x);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@dandavis - I added that option too.
Working perfect. Thanks a lot for the clear explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.