Solving Precedent at the Angle

Asked

Viewed 746 times

0

I am working on an application with Ionic 3 + Angular 5 and I have to take an Ionic Storage value as follows:

 this.userStorageService.get('expiresIn')
            .then((data) => this.tokenExpirationTimeFromApi = data);
 console.log(this.tokenExpirationTimeFromApi);

However when I do console.log outside of promisse it is returned 'Undefined', but if I put the console.log inside . then it returns normal. Then I made a setTimeOut:

this.userStorageService.get('expiresIn')
        .then((data) => this.tokenExpirationTimeFromApi = data);
    setTimeout(() => {
        console.log(this.tokenExpirationTimeFromApi);
    },1000);

That way it works, but I don’t think it’s the right thing to do. How do I get the value of the promise return and only then continue the application flow? Help, Please...

1 answer

0


Friend, what happens is that a Promise executes in a way asynchronous, that is, when you print the console.log on the next line outside the then() the value has not yet been recovered from Storage. The value is recovered correctly, just not at the moment you expect it to be, since it is mixing code synchronous with asynchronous.

To clarify more about the operation of the Promises take a look at documentation of Mozilla.

PS: Maybe if you post more details of your code it is possible to assist in a way to proceed.

PS2: The way to work with Promises is a little different than usual when you program more "procedural". A possibility for your code (not really knowing what you want to do) would be to return the result on then for a next callback and continue processing.


Follow a slightly more elaborate example this time, here I simulated a Storage that returns a Promise to a Provider, which processes this information and forwards a Promise with that amount already processed to the Controller who then uses a callback, which is not exactly necessary to update the View.

class Storage {
  constructor() {
    this.data = Math.random() * 10;
  }
  
  getData() {
    console.log("Buscando dados no storage..")
    return new Promise((resolve) => {
      // simula um tempo indeterminado para tarefa completar
      setTimeout(() => resolve(this.data), Math.random() * 3000);
    });
  }
}

class MyStorageProvider{
  constructor() {
    this.storage = new Storage();
  }
  
  fetchStorageData() {
    console.log("Chamando storage para pegar dados..");
    return this.storage.getData()
        .then(data => {
      console.log("Dados recuperados... verificando.");
      return data > 5;
    });
  }
}

class MyController {
  constructor() {
    this.output = document.querySelector('#output');
    this.provider = new MyStorageProvider();
  }
  
  requestDataFromStorage() {
    this.provider.fetchStorageData()
      // chamando o callback assim evita perder o escopo.
      // https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises
      .then(data => this.handleStorageData(data));
  }
  
  handleStorageData(data) {
    console.log("Processando dados para visão.. ");
    this.output.innerHTML = data;
  } 
}

var controller = new MyController();
controller.requestDataFromStorage();
<p id="output"></p>

  • I just want to get this expirationIn so I can then validate it with the current time. Type:

  • this.currentTime = new Date(). getTime(); this.tokenExpirationTime = new Date(this.tokenExpirationTimeFromApi). getTime(); Return this.currentTime > this.tokenExpirationTime;

  • I’ll try it the way you showed it...

  • It didn’t work, the problem is that I need to return a Boolean to the call of this method, like whether the current time is longer than expirationIn. I did using callback, but still returning Undefined.

  • take a look if the other example helps you.

  • It didn’t work. Here’s the thing, I need to take this value out of the then understand, because I need to make the method return as a Boolean. I’ve researched a million places, but no one has been able to explain to me exactly... I guess there’s no way

  • Dude, the call of the method is asynchronous. Vc can return a Promise with a Boolean as value and treat off. I can give you an angle example now. But as soon as I can update the answer. Tbm da para usar um callback. I’ll try to put together an example of the two cases for you to see later..

  • @Fellipebotelho I updated the answer with a more complete example, maybe clarify how you can work with asynchronous calls.

Show 3 more comments

Browser other questions tagged

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