0

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

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Quentin May 31 '21 at 12:55

1 Answers1

0

I found a working solution:

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', async (req, res) => {
    res.status(200).send({
        temp: await temp()
    })
});

async function temp() {
    result = await 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(error => console.log("This is an error: ", error));
    console.log("2: ", result);
    return Math.round(result* 100) /100;
}