I have written the following code to render some posts (which are stored in a Cloud Firestore instance). I am using mithril.js.
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
query.then(function (data) {
this.posts = data;
console.log("INSIDE VALUE: ");
console.log(this.posts);
});
console.log("OUTSIDE VALUE: ");
console.log(this.posts);
}
};
When I run my code, I obtain the following console output:
The value of this.posts
is different outside the function to the value of this.posts inside the function.
As the behaviour of this
can be confusing I have also tried the following code:
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
var x = [];
query.then(function (data) {
x = data;
console.log("INSIDE VALUE: ");
console.log(x);
});
console.log("OUTSIDE VALUE: ");
console.log(x);
}
};
The result of this code is the same:
In response to Chris Sandvik's answer I have also tried the following code
let SummaryPostView = {
posts: [],
view: function () {
let query = blogModels.postModel.getNLatest(20, "created");
query.then(function (data) {
this.posts = data.docs.map(function (doc) {
let out = doc.data();
out.id = doc.id;
return out;
});
console.log("INSIDE");
console.log(this.posts)
});
console.log("OUTSIDE");
console.log(this.posts);
}
};