How to get the LocalStorage value out of promise scope ionic 4


#1

So can you please correct me if i am wrong …

//Its working fine
this.storage.get(‘user_id’).then((result) => {
console.log(result);
});
//its not working
this.storage.get(‘user_id’).then((result) => {

});

console.log(result);


#2

Not sure what you’re asking here. Looks like there could be a syntax error?

Your console.log line is not within the promise callback, so it wouldn’t work in the second scenario.


#3

Thanks for your reply @tumain this is my actual code
getstorage()
{
this.storage.get(‘user_id’).then((result) => {
console.log(result);
});
}

let value =this.getstorage();

//then my output is like this

  1. ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

  2. __zone_symbol__state: true

  3. __zone_symbol__value: “5”

  4. proto: Object

then how can i get this value __zone_symbol__value: “5”


#4

i prefer the async/await syntax for promises, it feels easier to read
the method needs to return some value if you are assigning it to a variable

async getStorage(): Proimise<any> {
    try {
        const result =  await this.storage.get('user_id');
        console.log(result);
        return result;
    }
    catch(e) { console.log(e) }
}

let value = this.getStorage();

alternatively, without async:

getStorage() {
    return this.storage.get('user_id').then((result) => {
        console.log(result);
        return result;
    });
}

let value = this.getStorage();

do either of these work?


#5

Thanks @jjdev Checked
Nope!
same output i got

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

__zone_symbol__state: true
__zone_symbol__value: “5”
proto: Object


#6
let value: any;

getStorage() {
    try { return await this.storage.get('user_id') }
    catch(e) { console.log(e) }
}

this.getStorage().then((result) => {
    if (result) {
        console.log(result);
        value = result;
    }
});

Here I have just returned the promise entirely, and handle the ‘then’ outside of the method.

I’m not sure why this isn’t working for you, I haven’t had many problems using localStorage this way


#7

Thanks @jjdev I tried all your ways but only got this output

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

__zone_symbol__state: true
__zone_symbol__value: “5”
proto: Object


#8

Anyone having a idea ???


#9

Please try this,

let x = storage.get(‘user_id’)


#10

I would just double check here and make sure you have everything implemented properly

Storage docs


#11

Try this.

var result: any;

this.storage.get(‘user_id’).then((data) => {
 result = data
});
console.log(result);