0

I've been trying to get user locales using expo, on react-native. Problem is, i need to get the promise value and pass it to return function. The value is currently 'undefined'.

This is the code:

export default locales = () => {
  var locals;
  Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
    locals = value;
  });
return locals;
}

How do i get the promise value and return it on function?

Jacs
  • 1,437
  • 4
  • 21
  • 31
  • Are you trying to get this value to the parent scope or back to the caller? Those are different problems, though both are challenged by the indeterminate timing of the asynchronous operation that supplies the value and the fact that the function returns BEFORE the asynchronous value has been obtained (that's why you see `undefined`. – jfriend00 Oct 18 '18 at 00:14

1 Answers1

0

return locals; happens before your promise returns and so will be undefined. You need to use a callback:

export default locales = (callback) => {
  Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
    return callback(value);
  });
}

then you can access the value like this:

your_module.locales((locals)=>{
  // use locals here
});

or, if you have access to async/await in newer versions of node:

export default locales = async () => {
  let value = await Expo.DangerZone.Localization.getCurrentLocaleAsync()
  return value;
}

and then you would call the function like this:

let locals = await your_module.locales()

but, considering there is a function Expo.DangerZone.Localization.getCurrentLocaleAsync() are you sure a synchronous version, getCurrentLocaleSync() or getCurrentLocale() don't exist? That would make this much easier you could just call the function directly and obtain the value.

Christopher Reid
  • 4,318
  • 3
  • 35
  • 74