【问题标题】:Problem with asynchron return of readFile to API将 readFile 异步返回到 API 的问题
【发布时间】:2021-08-18 15:08:18
【问题描述】:

我正在从我使用 MQTT 发布的 Raspberry Pi 中读取数据,然后想使用发布 API 的服务器订阅,我以后可以在智能合约中使用它。

我现在的问题是,在 temp() 函数中,在将数据发送到 API 之前,我没有从全局变量中的 ReadFileContent 获取数据。我如何告诉 return 等到我有 ReadFileContent 函数的结果?

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;
}

输出:{"temp":0} 期望的输出 {"temp":46.82}

这是我的 github 存储库,以备不时之需。

https://github.com/GiraeffleAeffle/RPITempAPI

谢谢

【问题讨论】:

标签: api express asynchronous fs


【解决方案1】:

我找到了一个可行的解决方案:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-25
    • 2015-04-04
    • 1970-01-01
    • 2019-10-08
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    相关资源
    最近更新 更多