简体   繁体   English

使用aws-sdk时如何在AWS Lambda中进行异步/等待功能

[英]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 我正在使用AWS lambda从cloudwatch指标获取一些数据,以下是我在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 }'. 我总是先获得“ AAAA”,然后再获得“ DDDD $ {active_connection}”。

But what i want is get 'DDDD${active_connection }' first and then 'AAAA'. 但是我想要的是先获取“ DDDD $ {active_connection}”,然后获取“ AAAA”。

I tried to use like 我尝试使用像

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

but show 但显示

cloudwatch.getMetricStatistics(...).then is not a function cloudwatch.getMetricStatistics(...)。然后不是一个函数

Try writing your code like this, 尝试这样编写代码,

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

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

You could use util#promisify Docs 您可以使用util#promisify 文档

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM