I'm reading data from my Raspberry Pi which I publish with MQTT and then want to subscribe to with a server that publishes an API, which I can later use in a smart contract.
My problem is now that in the temp() function I don't get the data from the ReadFileContent in the global variable before it is sent to the API. How do I tell the return to wait until I have the result of the ReadFileContent function?
const express = require('express');
const app = express();
const PORT = 8080;
const fs = require('fs');
const util = require('util')
var average_temp = 0;
var avg = 0;
var result = 0;
const readFileContent = util.promisify(fs.readFile)
app.use(express.json())
app.listen(
PORT,
()=> console.log(`it's alive on http://localhost:${PORT}`)
)
app.get('/temp', (req, res) => {
res.status(200).send({
temp: temp()
})
});
function temp() {
readFileContent('tempdata.json')
.then(data=> {
obj = JSON.parse(data); //now it an object
objlength = Object.keys(obj).length;
for(let ii = 0; ii <= objlength-1; ii++){
average_temp += parseFloat(obj[String(ii)]);
}
average_temp /= objlength;
avg = average_temp;
average_temp = 0;
console.log("1: ",avg);
return avg;
})
.catch(console.error("Error!"));
return Math.round(avg* 100) /100;
}
Output: {"temp":0} Desired Output {"temp":46.82}
This is my github repository in case you need to try it out.
https://github.com/GiraeffleAeffle/RPITempAPI
Thanks