Node.js Lambda异步返回未定义

时间:2019-01-01 00:02:28

标签: node.js lambda

对ec2的简单调用,描述安全组并返回安全组ID。使用异步/等待,但是记录返回值时,我不确定。我完全承认我来自Python,我尽了最大的努力来使我的大脑围绕异步调用。我以为自己已经被钉住了,但是我显然缺少了一些东西。

'use strict';

// Load Modules
const AWS = require('aws-sdk')

//Set the region
AWS.config.update({region: 'us-west-2'});

// Call AWS Resources
const ec2 = new AWS.EC2();

// Get Security Group ID From Event
const getSgIdFromEvent = async (event) => {
  var ec2params = { Filters: [{Name: 'tag:t_whitelist',Values[event['site']]}]};
  await ec2.describeSecurityGroups(ec2params, function (err, response) {
    if (err) {return console.error(err.message)}
    else {
      var sgId = response.SecurityGroups[0].GroupId;
      return sgId;
    };
  });
 };
// MAIN FUNCTION
exports.handler = (event, context) => {
  getSgIdFromEvent(event)
   .then(sgId => {console.log(sgId)});
}

“ sgId”应返回安全组ID。在返回之前,它确实可以在原始函数中很好地打印出来。

3 个答案:

答案 0 :(得分:1)

通常,如果它是一个异步调用,您希望以这种方式处理它而不使用回调

// Load Modules
const AWS = require('aws-sdk')

//Set the region
AWS.config.update({ region: 'us-west-2' });

// Call AWS Resources
const ec2 = new AWS.EC2();

// Get Security Group ID From Event
const getSgIdFromEvent = async (event) => {
    var ec2params = { Filters: [{ Name: 'tag:t_whitelist', Values[event['site']]}] };
    try {
        const securityGroupsDesc = await ec2.describeSecurityGroups(ec2params).promise();
        const sgId = securityGroupsDesc.SecurityGroups[0].GroupId;
        //do something with the returned result
        return sgId;
    }
    catch (error) {
        console.log('handle error');
        // throw error;
    }
});
 };
// MAIN FUNCTION
exports.handler = (event, context) => {
    getSgIdFromEvent(event)
        .then(sgId => { console.log(sgId) });
}

但是,如果它不支持异步,则只需使用回调函数即可处理返回的数据或错误,而无需使用异步函数。但是,通过阅读AWS文档,您会发现函数ec2.describeSecurityGroups()返回了{{3} } 该方法具有AWS Request方法,需要调用该方法来发送请求并返回承诺。请注意,此处不需要try catch,但最好在处理过程中发生错误时使用。

答案 1 :(得分:0)

正如我在评论中所说,describeSecurityGroups可能不会返回Promise。尝试在Promise中显式转换它:

const promiseResponse = await new Promise((res, rej) => {
  ec2.describeSecurityGroups(ec2params, function (err, response) {
    if (err) {return rej(err.message)}
    else {
      var sgId = response.SecurityGroups[0].GroupId;
      res(sgId);
    };
  })
});

// promiseResponse is now equal to sgId inside the callback
return promiseResponse; // this will work because the function is async

注意:您可以删除else关键字

答案 2 :(得分:0)

这是使用async / await的代码。多亏@Cristian Traina,我才意识到ec2.describeSecurityGroups并没有兑现承诺,而是返回了AWS.Event

// Get Security Group ID From Event
const getSgIdFromEvent = async (event) => {
  console.log('Getting Security Group ID')
  var params = { Filters: [{Name: 'tag:t_whitelist', Values 
   [event['site']]}]};
  const describeSG = await ec2.describeSecurityGroups(params).promise();
  return describeSG.SecurityGroups[0].GroupId;
 };

// Get Ingress Rules from Security Group
const getSgIngressRules = async (sgId) => {
  console.log(`Getting SG Ingress rules for ${sgId}`)
  var params = { GroupIds: [ sgId]};
  try{
    const ingressRules = await ec2.describeSecurityGroups(params).promise();
    return ingressRules;
  }
  catch (error) {
    console.log("Something went wrong getting Ingress Ruls");
  }
 };

// MAIN FUNCTION
exports.handler = (event, context) => {
  getSgIdFromEvent(event)
  .then(sgId => {return getSgIngressRules(sgId);}) 
  .then(ingressRules => {console.log(ingressRules);});
}

我现在将其作为答案提交,因为我拥有的getSgIdFromEvent函数只有8行,并且像我想要的那样仍在使用async/await

我所缺少的是函数末尾的.promise()并返回了那个承诺。

感谢所有回复!