0

I hope your are healthy and well. I am developing a simple mobile application using ionic and react. I am using sql database and for this purpose I created Api's for user registration and login. Whenever a user login, app stores user session using local Storage. [Code for storing session]

Storage.set({
  key: 'currentUser',
  value: username
});

No the problem is this: [Code for retrieving stored values]

let session;
Storage.get({ key: 'currentUser' })
.then(p1 => {
  const p2 = p1.value;
  const p3 = p2.replace(/"/g, "");
  session = p3;

});

console.log(session) //This gives 'undefined'

Here variable (p3) contains actual username. But when I assign its value to session variable. The session variable becomes undefined. I don't know how to get session value out of this function. Please help me to fix this. Thanks

Awais Khalid
  • 86
  • 1
  • 8

2 Answers2

1

I think you can't. The code wrapped in then() is executed asynchronously, meaning you don't know what is executed first: session = p3 or console.log(session). Maybe this queestion will help? How to access the value of a promise?

mkasp98
  • 164
  • 1
  • 6
0

Javascript is an asynchronous language. Here your request will take some time before arriving and that's why javacript is going to ignore the function then(). You can see this process using the setTimeout function that emulate your API call:

let session;

setTimeout(() => {
  // This will be executed after 500ms but javascript go ahead and execute the other console log
  session = 'test';
  console.log(session);
}, 500);

console.log(session) // Is executed first
johannchopin
  • 13,720
  • 10
  • 55
  • 101