-1

I am developing an app with Intel XDK and Cordova.

At the beginning of the code, I use these lines to get the preferred language from the device and store it into a variable named "lang":

navigator.globalization.getPreferredLanguage(
                function (language) {
                    lang = language.value;
                },
                function () {alert('Err');}
            );

Then I have some lines of code where I need this variable "lang" and its value, but for some reason, this function is being executed at the end, so during all the code execution lang is equal to null.

Is there any way to make sure this function is completed and lang has its value, before continuing?

Cœur
  • 37,241
  • 25
  • 195
  • 267
garfield185
  • 213
  • 2
  • 11
  • You generally have to wait until after the deviceready event is dispatched before interacting with any Cordova API's. That is most likely the case here. – Ian Maffett Mar 26 '15 at 12:26
  • This code is being executed after the deviceready event. Thank you. – garfield185 Mar 26 '15 at 12:42
  • 1
    Ok - the other part is the function call will be asynchronous, so it will execute in the background and the rest of your calls will execute. If you need there result, move that code into the function(language){} part – Ian Maffett Mar 26 '15 at 13:05
  • I see... Isn't there any other function that returns the same value, without the need of an asynchronous function? It would be much more simple if the getPreferredLanguage function returned directly that language.value string – garfield185 Mar 26 '15 at 13:32
  • Not that I know of. The plugins make native calls to get this value. It is not exposed by the WebView. https://github.com/jcfischer/pgkitchensink/blob/master/plugins/org.apache.cordova.globalization/src/ios/CDVGlobalization.m – Ian Maffett Mar 26 '15 at 13:48

1 Answers1

0

Yes, as Ian said in the comments, just move all the code you need to execute after it into the function below this line of code: lang = language.value;

You can nest multiple asynchronous calls this way too.

K'shin Gendron
  • 1,589
  • 1
  • 12
  • 14