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

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);

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.

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”

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?

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

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

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

Anyone having a idea ???

Please try this,

let x = storage.get(‘user_id’)

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

Storage docs

Try this.

var result: any;

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

you do not use a promise value directly.
you either use it in it’s then/catch method with callback,
or use it with await inside async block.

you may learn more about async programming in javascript from this youtube video: