Resolving non-angular promise

0

I'm working on an application with Ionic 3 + Angular 5 and I have to get an Ionic storage value as follows:

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

However when I make the console.log out of the promisse it is returned 'undefined', but if I put the console.log inside the .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 do not think it's the right thing to do. How do I get the value of the return from promisse and only from there continue the flow of the application? Help, please ...

    
asked by anonymous 14.03.2018 / 12:27

1 answer

0

Friend, what happens is that Promise executes asynchronously , that is, when you start console.log on the next line out of then() the value has not yet been retrieved of storage. The value is retrieved correctly, just not the moment you expect it to be, since you are mixing synchronous code with asynchronous .

  

To clarify more about the operation of the Promises, read the    mozilla documentation.

PS: Maybe if you post more details of your code you can help in a way to proceed.

PS2: Working with Promises is a bit different from usual when you program in a more "procedural" way. One possibility for your code (not really knowing what you want to do) would be to return the result in then to a callback and continue processing.

Here is a slightly more elaborate example of this time, here I simulated a Storage that returns a promise to a Provider , which processes this information and forwards a Promise to this already processed in> to Controller which 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>
    
14.03.2018 / 12:43