简体   繁体   中英

javascript how to get function return value out of argument function

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

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

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