Get the value of a promise

3

I'm having a lot of trouble getting the value of a promise . Basically I want the value that returns a promise to be assigned to a variable. For example

  

This example uses the following elements: , , almacen is a synonym from localForage , a package to use with local storage.

With this code I get the error Cannot read property 'getItem' of undefined

let _accessToken = this.almacen.getItem('token')

Then I use a function .then() and I get the same error above

let _accessToken = this.almacen.getItem('token').then(carga => carga)

Then I convert my variable _accessToken into a function.

let _accessToken = () => this.almacen.getItem('token').then((carga) => carga)

Here I do not have any syntax errors, but the variable to be evaluated returns an error, which says (error during evaluation) .

Now, if I do a function and use the promise inside, if it works. For example:

function _getAccessToken () {
  this.almacen.getItem('token')               // consulto el almacenamiento
    .then((payload) => {                      // obtengo el resultado
      if (payload) {
        this.$store.state.token = payload     // lo guardo en una variable global
        this.$store.state.fuera = false       // altero otra variable
      } else this.$store.state.fuera = true
    }).catch((e) => console.log('Error ${e}'))
}

Here everything works as expected, but I insist on using my variable, so I added it:

let _accessToken = ''                            // declaro mi variable

function _getAccessToken () {
  this.almacen.getItem('token')
    .then((payload) => {
      if (payload) {
        _accessToken = payload                   // Aqui intento asignar la promesa
        this.$store.state.token = payload
        this.$store.state.fuera = false
      } else this.$store.state.fuera = true
    }).catch((e) => console.log('Error ${e}'))
}

When evaluating the function, I get an error:
Uncaught TypeError: Cannot read property 'toString' of undefined .

The truth is I'm just guessing and I can not reach it.

How can I save the value of the promise in the indicated variable?

Edit

So that you can observe the operation of the application I created a small jsfiddle that reproduces the problem:

link

    
asked by toledano 27.03.2017 в 04:06
source

2 answers

3

Ok, I wanted to learn how to use Vue.js and I did not think I was going to start from back to front so, first of all, I do not know what I'm doing about observables, computed or data properties. I apologize in advance if the solution is crude.

What I can tell you is that to get the value of the promise you must always return . So where it says:

function _getAccessToken () {
  localforage.getItem('token')
    .then((payload) => {
      if (payload) {
        this.$store.state.token = payload
        this.$store.state.fuera = false
      } else this.$store.state.fuera = true
    }).catch((e) => console.log('Error ${e}'))
}

You are not returning anything. That function always assigns an undefined value.

If instead he said:

function _getAccessToken () {
  return localforage.getItem('token')
    .then((payload) => {
      if (payload) {
        this.$store.state.token = payload
        this.$store.state.fuera = false
      } else {
        this.$store.state.fuera = true
      }
      return payload;
    }).catch((e) => console.log('Error ${e}'))
}

Then you could say:

var app = new Vue({
  el: '#app',
  store,
  mixins: [sessionService],
  computed: Vuex.mapState(['token', 'fuera']),
  mounted () {
    this.getAccessToken().then((token)=>{
        this.accessToken=token;
    })
  }
})

And it would look in your template.

I left you a fiddle

link

However, returning to your original fiddle, it seems that you can opt for a shorter and perhaps dirty solution that is to directly assign this.accessToken within the _getAccessToken method by doing:

function _getAccessToken () {
  localforage.getItem('token')
    .then((payload) => {
      if (payload) {
        this.accessToken = payload     // <-- asignación directa
        this.$store.state.token = payload
        this.$store.state.fuera = false
      } else this.$store.state.fuera = true
    }).catch((e) => console.log('Error ${e}'))
}

And that works the same. But again, that is not the way to work with a promise, because the idea is that _getAccessToken is thenable for any other use and resolves to the value of the token. This last workaround only takes advantage of a side effect and I would not use it that way.

    
answered by 27.03.2017 / 13:25
source
0

I had the same problem with Axios. I could neither send nor receive any data that Axios handled and I saw the information inside Axios but I could not work it out.

I started reading about promises and, I concluded, that this technology always evaluates the operation for success or failure first . If there is an error, it never goes through the function of .then and if it succeeds it does so.

I always had the same error

  

Can not read property 'xxxx' of undefined

and it was because the assignment was never configured or when the assignment was made had not entered the data (asynchronism). When returning the answer to another .then one is assured of taking the data.

axios().then(response => {return response}.then{respuesta => { this.dato = respuesta}.catch{...}
    
answered by 12.11.2017 в 23:46