Value showing null when used outside get() in Storage

this.storage.get('ls.user').then( (val) => {
  this.user= val;
  console.log("the selected option is =>", this.user);   // here the value of user is "admin"
  this.translate.use(this.user);   
});

console.log(this.user); // here the value of the user is NULL

i use the value of val …but not able to use it…
any ideas how to use val value even outside the get() ?

1 Like

every time you see something like this:

myFunction().then(....)

or

myFunction(callbackFunction());

then myFunction is doing some asynchronous work --> so it could take some or more time to execute this function.
But JavaScript runs to completion --> it start in your first line of code and goes through your code --> means the browser does not wait until the callback of then() is called. it start the this.storage.get() function and goes on for your console.log. And at some point this.storage.get() has finished and calls the callback you defined in then()

Thanks sir…solved my issue…

Do you mind showing what your code looks like now to use that value outside the get method?

this.storage.get('ls.user').then( (val) => {
  this.user= val;
  console.log("the selected option is =>", this.user);   // here the value of user is "admin"
  this.translate.use(this.user);   

//MOVED MY CODE HERE FROM OUTSIDE THE BLOCK and its working file AS FOLLOWS

if(this.user !== null){
     alert("success");  // sSHOWS ALERT
}
else{
   alert("unsuccessful");
}


});

console.log(this.user); // here the value of the user is NULL
   //OLD CODE WAS HERE

Ohh I see, thats how I do it too, was just curious if there was another way.

Thanks.

There are no “tricks” involved here. You cannot rely on the value from storage except within the then clause. You cannot return it from getStartTime. Simply. Not. Possible.