I'm new to Node so I'm struggling with getting the data from one function to another:
//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
});
};
...
I tried using async/await in dataController as well - no luck. Old callback-way works, however I rather keep things consistent and use async/await.
Can somebody help me out here? What am I missing? My guess is that in my dataController the results are not in the event loop yet. However 'awaiting' them did not help.
UPD:
Guys, thanks, I tried this from the very beginning:
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 result:
{
"status": "success",
"message": "Here we will have all sensors object"
}
asynckeyword ingetAllReadingsand then useawaitbeforedhtController.currentTemperature()currentTempis notundefined, it is an instance ofPromise. If youJSON.stringify({ currentTemp: new Promise(() => {}) })you get"{\"currentTemp\":{}}", not"{}", so I'm not sure what leads you to thinkcurrentTempisundefinedexports.getAllReadings = async (req, res, next) => { const currentTemp = await dhtController.currentTemperature();returns 'undefined'asyncfunctions always return promises, no exceptions. Please produce a minimal reproducible example because I'm certain either you're mistaken, or your example code is not representative of the situation.dhtSensor = require('node-dht-sensor')ordhtSensor = require('node-dht-sensor').promises? If it's the former, that's your mistake.