0

Im using .then when getting item from Asyncstorage/localstorage. I want to use the item I get from storage, but can't because I only get the unresolved promise. Also, I cannot use async/await as Im not using it inside a function in my case.

const language = AsyncStorage.getItem('user').then(item => item).then(user => {
    const lang = JSON.parse(user).lang;
    console.log("item:", lang, typeof lang)
    return lang;
});
console.log("language: ", language)

output:

language: Promise {
  "_A": null,
  "_x": 0,
  "_y": 0,
  "_z": null,
}

item: de
learningcoding
  • 187
  • 2
  • 14
  • The whole point of `then` is that the callback is called at some point in the future when the promise is resolved. We don't have time travel. You can't return `lang` **from a function that hasn't run yet** and assign it to `language` now. – Quentin Apr 11 '23 at 09:48
  • thank you, I understand. Could you tell me what I can do then instead to be able to use the resolved promise? – learningcoding Apr 11 '23 at 09:53
  • Use a `then` callback. – Quentin Apr 11 '23 at 09:54
  • Im not sure where to attach the callback? I need to save the value not just use it inside a callback. – learningcoding Apr 11 '23 at 10:03
  • To the `language` variable because it holds the promise. You cannot save the value, it doesn't exist at the time you are trying to save it. You can save the promise. – Quentin Apr 11 '23 at 10:04
  • if I do the following: const value = language.then((val) => val) so attaching a .then to language, then I still only see a not resolved promise when logging value – learningcoding Apr 11 '23 at 10:07
  • I refer you to my first comment. `then` will always return a promise. – Quentin Apr 11 '23 at 10:08
  • i understood your first commend. All I want to know is if there is a way to save the resolved promise. You say using callback. I ask how can I use a callback, to again, save the outcome, you say use .then callback,you say to the language variable, I say it will still not have me save the outcome only the unresolved promise.then you say refer to my first comment. Can I understand from your comments that it is the not possible to save the resolved promise in a variable because you say that in your first comment or again, is there a solutin, how I can save a resolved promise –  Apr 11 '23 at 10:45

0 Answers0