alexortizl
alexortizl

Reputation: 2690

Get AWS IoT shadow state from AWS Lambda

I'm trying to get the a IoT shadow state from inside a Lamda function. This is what I have so far in my Lambda function:

var AWS = require('aws-sdk');

var iotdata = new AWS.IotData({
  endpoint: process.env.endpoint
});

exports.handler = async (event) => {
  const params = {
  thingName: 'MyThing',
};

iotdata.getThingShadow(params, function(err, data) {
  if (err) console.log(err, err.stack); 
  else     console.log('ok', data);        
});

But it never logs the data. What am I missing?

Upvotes: 1

Views: 673

Answers (1)

Marcin
Marcin

Reputation: 238249

Since you are using async handler I think the issue is that your function completes before handler's body has a chance to run.

One way to rectify this is through the use of Promise as shown in AWS docs. For example:

var AWS = require('aws-sdk');

var iotdata = new AWS.IotData({
  endpoint: process.env.endpoint
});

exports.handler = async (event) => {

    const promise = new Promise(function(resolve, reject) {

      const params = {
        thingName: 'MyThing',
      };

      iotdata.getThingShadow(params, function(err, data) {
        if (err){
           console.log(err, err.stack); 
           reject();
        }
        else {
           console.log(data);
           resolve();
        }        
      });
  })

  return promise;  

Upvotes: 4

Related Questions