简体   繁体   中英

Why does this JavaScript function always returns 'undefined' – and how to fix that?

I'm using phonegap with application preferences plugin and trying to make a helper function to get a value from it. However the function is not returning a correct value. I know this has to do with asynchronous thingy but unfortunately I don't know how to fix it. (I've tried to search help here, and found little, and tried to implement it in helper method)

What I want to achieve is:

function populateList() {
    var a = 1;

    var number = getSettingFromApplicationPreferences('number');
    // number is always undefined

    var letter = getSettingFromApplicationPreferences('letter');
    // letter is always undefined

    number = (number) ? number : 1;
    letter = (letter) ? letter : 'b';

    // Here I'll do some DOM manipulation and use 'number' and 'letter' on it, and 
    // define new variables based on 'number' and 'letter'

}

here's the helper function that I need help with:

function getSettingFromApplicationPreferences(setting) {

    var x = (function () {
        window.plugins.applicationPreferences.get(
            // setting
            setting, 
            // success callback
            function(returnValue) {
                console.log(setting + ': ' + returnValue);
                return returnValue;
            },
            // error callback
            function(error) {
                alert("Failed to get a setting: " + error);
                return false;
            }
        );
    })();

    return x;   
}

Question
How is it possible to return the 'returnValue' from application preferences with that helper function?

The problem is, your callback doesn't actually set a value for x. So, you're going to have some other way to do whatever you're doing, because return values will not work.

You are using an asynchronous function incorrectly, you cannot assign like you are because the function hasn't returned yet and so you get an undefined. You need to use a callback function instead.

That means that inside the success function you would do whatever you need to do with the "returnValue".

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