I'm totally new to nodejs coming from a vb.net background. I've looked at so many examples of using callbacks but I just don't get it. So sorry if this is very basic.
I'm writing a AWS Lambda function and trying to get a value from a AWS IOT Thing Shadow and assign it to a variable. But I can't get it to work, however the log does show that the value was returned. I know it has to do with sync/async, but just lost the plot to how to get it. Here is the code so far:
//determine doorstate
function getdoorstate() {
//ask the thing
var currentstate;
var paramsGet = {
"thingName": "garagedoor1",
};
iotData.getThingShadow(paramsGet, function (err, data) {
if (err) {
console.log("Error : " + err, err.stack);
} else {
console.log(data.payload);
var obj = JSON.parse(data.payload);
currentstate=obj["state"]["reported"]["doorstate"];
console.log("The function doorstate is: "+currentstate);
}
});
}
var doorstate = getdoorstate();
The log shows the console writes fine (presume they happen after the data has been retrieved):
INFO {"state":{"desired":{"doorstate":0,"transitstate":0},"reported":{"doorstate":0,"transitstate":0}},"metadata":{"desired":{"doorstate":{"timestamp":1591241517},"transitstate":{"timestamp":1591241517}},"reported":{"doorstate":{"timestamp":1591241517},"transitstate":{"timestamp":1591241517}}},"version":444,"timestamp":1591241860}
The function doorstate is: 0
However the value returned is: undefined
Can anyone suggest how to change my code to use callback properly. Make it simple - I'm new! Thanks!
UPDATED CODE AS SUGGESTED BY Sagar - STILL ISSUE
//determine doorstate
function getdoorstate() {
//ask the thing
var paramsGet = {
"thingName": "garagedoor1",
};
iotData.getThingShadow(paramsGet, function (err, data) {
if (err) {
console.log("Error : " + err, err.stack);
} else {
callback(data)
}
});
}
getdoorstate(function (value){
console.log(value);
});
var doorstate = getdoorstate();
What am I doing wrong again?