Ko7
Ko7

Reputation: 127

How to use async function to call pinpoint.getUserEndpoints in AWS lambda

I am using pinpoint api to get a user endpoints. My code looks like this.

const AWS = require('aws-sdk');
const pinpoint = new AWS.Pinpoint()

exports.handler = async (event, context) => {
      console.log(JSON.stringify(event, null, 2));
      event.Records.forEach(record => {
        console.log(record.eventID);
        console.log(record.eventName);
        const params = {
         ApplicationId: "secret", /* required */
         UserId: "userId"/* required */
        };
        try {
        var result = pinpoint.getUserEndpoints(params).promise();
        console.log('data',result);
      }
        catch (err) {
            console.log(err);
            return
        }
       })
      context.done(null, 'Successfully processed DynamoDB record'); // SUCCESS with message
    };

I checked the cloud watch log and it says data Promise { <pending> }

I also tried this inside forEach.

var result = pinpoint.getUserEndpoints(params).promise();
    result.then(function(data) {
  console.log('Success',data);
}).catch(function(err) {
  console.log('err',err);
});

But I couldn't find any logs in Cloud Watch from this part.

How can I call this async function properly using pinpoint.getUserEndpoints(params).promise();?

Upvotes: 1

Views: 462

Answers (1)

LostJon
LostJon

Reputation: 2387

You're kinda dancing all around the answer with your initial post. Try the below:

const AWS = require('aws-sdk');
const pinpoint = new AWS.Pinpoint()

exports.handler = async (event, context) => {
    console.log(JSON.stringify(event, null, 2));
    await Promise.all(event.Records.map(async (record) => {
        console.log(record.eventID);
        console.log(record.eventName);
        const params = {
            ApplicationId: "secret", /* required */
            UserId: "userId"/* required */
        };
        const result = await pinpoint.getUserEndpoints(params).promise().catch(console.log);
        console.log('data', result);
    }));
    return 'Successfully processed DynamoDB record'; // SUCCESS with message
};

Upvotes: 2

Related Questions