Dreams
Dreams

Reputation: 8506

How to make a async/await function in AWS Lambda when using aws-sdk

I am using AWS lambda to get some data from cloudwatch metric and below is my code in lambda

var AWS = require('aws-sdk');    
AWS.config.update({region: 'ap-northeast-1'});
var cloudwatch = new AWS.CloudWatch({apiVersion: '2010-08-01'});

exports.handler = async function(event, context) {
    console.log('==== start ====');
    const connection_params = {
      // params
    };

    cloudwatch.getMetricStatistics(connection_params, function(err, data) {
        if (err){
            console.log(err, err.stack);  
        } else {
            console.log(data);      
            active_connection = data.Datapoints[0].Average.toFixed(2);
        }   
        console.log(`DDDDDDD ${active_connection}`);
    });

    console.log('AAAA');    
};

I always get 'AAAA' first and then get 'DDDD${active_connection }'.

But what i want is get 'DDDD${active_connection }' first and then 'AAAA'.

I tried to use like

cloudwatch.getMetricStatistics(connection_params).then(() => {})

but show

cloudwatch.getMetricStatistics(...).then is not a function

Upvotes: 0

Views: 307

Answers (2)

zerosand1s
zerosand1s

Reputation: 750

Try writing your code like this,

  1. With then
    const x = cloudwatch.getMetricStatistics(connection_params).promise();

    x.then((response) => do something);
  1. With async/await
    const x = await cloudwatch.getMetricStatistics(connection_params).promise();

Upvotes: 2

wiomoc
wiomoc

Reputation: 1089

You could use util#promisify Docs

const util = require("util");
const cloudwatch = new AWS.CloudWatch();

const getMetricStatistics = util.promisify(cloudwatch.getMetricStatistics.bind(cloudwatch));

getMetricStatistics(connection_params).then(() => {})

Upvotes: 0

Related Questions