How to get a Promise value in JavaScript / TypeScript?

1

I'm starting with Ionic 2, which uses Angular 2, and I'm trying to understand how promises work, since some libs I'm using work have functions that return promises and would like to get the value returned, but 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 return this way? Thank you for your attention.

    
asked by anonymous 06.06.2016 / 21:17

2 answers

3

This happens because your get function returns nothing, notice that your return is inside an anonymous function and not in the get function

In general, Promises are used in asynchronous programming, it's basically an alternative to callbacks, where you're actually using callbacks, one way to fix your problem would be by returning Promise in 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 resolved

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

Now depending on whether 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 still not supported by most browsers and I can not say in the case of Ionic 2 how the support is or if you need to use a transpiler like Babel

    
09.08.2016 / 14:14
1

Try this:

...
localforage.getItem(key).then((value) => {
...
    
09.08.2016 / 13:25