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: vue. js , vuex ,
almacen
is a synonym fromlocalForage
, 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: