0

I use AWS Service IotData in AWS Lambda function, so I use AWS SDK, the IotData service needs to provide an iot endpoint configuration parameter when constructing IotData service, so I use another service to get endpoint, the code is as follow.

const AWS = require('aws-sdk');
const iot = new AWS.Iot();
const endpoint = iot.describeEndpoint(
{
    endpointType: 'iot:Data-ATS'
}).promise();

const iotdata = new AWS.IotData({endpoint:endpoint});

exports.handler = async (event, context, callback) =>
{
    // code goes here...
}

I tried to use iot function describeEndpoint to get the endpoint, and assign the value to variable endpoint.

I understand that it will fail, because the variable endpoint will get a promise object. Therefore, I tried async IIFE to get endpoint:

const endpoint = (async () => {
    let result = await iot.describeEndpoint(
    {
        endpointType: 'iot:Data-ATS' 
    }).promise();
    return result;
})();

However, it also gets promise object as a result.

Is there any other solution to get value from an asynchronous call?

P.S The reason why I am asking is that I am trying to put variable endpoint and iotdata on top level, because I am afraid that these variable might be used by other functions.

Lionel
  • 33
  • 5
  • lots of good content and probably your answer in https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Andrew Lohr Sep 10 '19 at 17:29
  • 2
    If it's returns a promise then you can probably just do `const endpoint = await iot.describeEndpoint(` – Matt Aft Sep 10 '19 at 17:30
  • @AndrewLohr: I already read this post, and it doesn't meet my need. @MattAft: no, `await` is only valid in async function, but I want the variable `endpoint` and `iotdata` on top level, so it shouldn't in any other function. – Lionel Sep 10 '19 at 20:03

1 Answers1

0

You need the await in the level where you want the endpoint.

Something like: (untested)

    const getEndpoint = async () => {
        let edp = await iot.describeEnspoint(
             {endpointType: 'iot:Data-ATS'})
             .promise();
        return edp.endpointAddress;
        };

...
    let iotDataEndpoint = await getEndpoint();
    let iotData = new AWS.IotData({endpoint: iotDataEndpoint});

You can't make iotData a top level const (unless you hard-code the endpoint) because you have to wait for the describeEndpoint call to return before creating it.