I am writing an amateur SPA, based on Vue (specifically the Quasar framework).
This application, in mounted()
, connects to an MQTT broker to get some information (MQTT does not matter here - it could be an API called with fetch()
, the point is that the results are available "after some time" in JS asynchronous way). This information is stored in this.results
.
I use this.results
in some components and the content is displayed as expected, and updated upon new results (i.e. a change in this.results
) as expected as well.
Since this a front end for a home monitring program, I wanted to also display the last time the results were fetched and raise alerts if I did not get new results for some time (that would suggest that the monitoring backend itself crashed). I went for:
mounted() {
// connect to the MQTT broker = new results will come. That could be a setInterval fetch()
this.client = mqtt.connect("mqtt://mqtt.swtk.info:1884");
this.client.on("connect", this.mqttConnect);
this.client.on("message", this.mqttMessage);
// check every 900 ms for the last time I got the results, and set a variable for the elapsed time
setInterval(
function() {
console.log(this.results)
this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
},
900
)
}
This is the message I continuously (every second) get on the console:
At the same time, this.results
is defined: not only cntents from this.results
are otherwise correctly displayed in components, but when looking at the DevTool Vue tab, I
I see:
It looks like the this.result
in the setInterval()
function is assessed only once and is undefined
- which is fine because it would not have been received at that time yet, but will shortly be set (upon getting the first results).
Shouldn't its value be used as it is "currently" in each of the 900 ms calls to the function?