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>