How to get the return (value) of a Promise in Javascript / Typescript?

Asked

Viewed 2,784 times

1

I’m starting with Ionic 2, which uses Angular 2, and I’m trying to understand how Promises work, because some libs I’m using work have functions that return Promises and would like to get the value returned, however the return is always Undefined:

Ex.:

'class' Storage:

public get(key: string) {
    localforage.getItem(key).then(function (value) {

      console.log(value); // exibe o value normalmente, ex.: {nome: 'Joao', idade: '20'}
      return value;

    }).catch(function (err) {
      console.log(err);
    });
}

'class' Page1:

recuperarItem() {
    var object = this.storage.get('pessoa1');

    console.log(object); // undefined
}

How do I get the return this way? Thank you for your attention.

  • Wouldn’t that be the part localforage? The correct is localStorage

  • I’m using the localforage library in this example - https://mozilla.github.io/localForage/ - but the doubt would apply to any Promise

2 answers

3

This happens because its function get does not return anything, note that your Return is inside an anonymous function and not in the function get

In general Promises are used in asynchronous programming, it is basically an alternative to callbacks, where in fact you are still using callbacks, one way to fix your problem would be by returning the Promise in function get

public get(key: string) {
    return localforage.getItem(key).catch(function (err) {
        console.log(err);
    });
}

And then in function recuperarItem you expect the Promise to be solved

recuperarItem() {
    this.storage.get().then(function (value) {
        console.log(value);         
    })
}

Now depending on if the Typescript target is es6/es2015 you have the option to use async/await, your code would look like this

public get(key: string) {
    return localforage.getItem(key).catch(function (err) {
        console.log(err);
    });
}

And then in function recuperarItem we let Typescript do its magic with async await

async recuperarItem() {
    var object = await this.storage.get();
    console.log(value);         
}

But remembering that es6/es2015 is not yet supported by most browsers and can not say in the case of Ionic 2 how is the support or if you need to use some transpiler as the Babel

  • The problem was just what you said. At that time I didn’t know how to work with Precedents yet, and you clarified well, thank you! Sorry for the delay in returning.

1

Try this way:

...
localforage.getItem(key).then((value) => {
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.