我是 Node 新手,所以我正在努力将数据从一个函数获取到另一个函数:
//dhtController.js
const dhtSensor = require('node-dht-sensor').promises;
exports.currentTemperature = async () => {
const rawTemp = await dhtSensor.read(22, 4); // { temperature: 24, humidity: 60 }
return rawTemp;
};
//dataController.js
const dhtController = require('./dhtController');
...
exports.getAllReadings = (req, res, next) => {
const currentTemp = dhtController.currentTemperature(); // undefined
res.status(200).json({
status: 'success',
currentTemp, // undefined
});
};
...
我也尝试在 dataController 中使用 async/await - 没有成功。 旧的回调方式有效,但我宁愿保持一致并使用 async/await。
有人可以帮我吗?我缺少什么?我的猜测是,在我的 dataController 中,结果尚未在事件循环中。然而“等待”他们并没有帮助。
更新:
伙计们,谢谢,我从一开始就尝试过:
exports.getAllReadings = async (req, res, next) => {
const currentTemp = await dhtController.currentTemperature();
console.log(JSON.stringify({ currentTemp: new Promise(() => {}) }));
//{"currentTemp":{}}
res.status(200).json({
status: 'success',
message: 'Here we will have all sensors object',
currentTemp, // empty
});
};
postman 结果:
{
"status": "success",
"message": "Here we will have all sensors object"
}
最佳答案
由于您调用的函数使用了await,因此您需要将调用的函数设为异步。这是有道理的,因为您正在等待结果。
exports.getAllReadings = async (req, res, next) => {
const currentTemp = await dhtController.currentTemperature();
res.status(200).json({
status: 'success',
currentTemp, // undefined
});
};
关于javascript - NodeJS 函数返回数据的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397718/