首页 > 解决方案 > 为什么我的 Node.js AWS Lambda 函数只能每隔一段时间工作一次?

问题描述

我有一个创建快照副本的 Node.js Lambda 函数。问题是它仅在每隔一次被调用时才有效。我认为问题与我没有通过 async / await 正确处理代码的异步部分有关。但我无法弄清楚问题是什么。

从未发现任何错误。我已将超时值设置为 35 秒,这应该足够了。无论是否创建快照,记录的输出都是相同的。 但是仅在我第二次运行该功能时才创建快照!?

谁能告诉我发生了什么?谢谢。

使用 AWS 中可用的最新版本的 Node.js。

var AWS = require("aws-sdk");
AWS.config.update({region: 'eu-west-2'});
const ec2 = new AWS.EC2();
const dst_account = "xxxxxxxxxxxx";
const src_account = "yyyyyyyyyyyy";

async function get_all_snapshots(owner){
    console.log("*** get_all_snapshots() entered");
     
    var params = {
       Filters: [{
         Name: "status", Values: [ "completed" ]
       }],
       MaxResults: 5,       // Minimum value, as just need the last one.
       OwnerIds: [ owner ]
     }; // end params
         
    try {
       var snapshots = await ec2.describeSnapshots(params).promise();
       return snapshots;
    } catch (err) {
        throw Error(err);
    }
} 

async function copy_snapshot(id){
 
    console.log("*** copy_snapshot() entered", id);
     
    var params = {
        Description: "Snapshot created by Lambda Function", 
        DestinationRegion: "eu-west-2", 
        SourceRegion: "eu-west-2", 
        SourceSnapshotId: id
    }; // end params
     
    try {
       var ss = await ec2.copySnapshot(params).promise();
       console.log("*** ec2.copySnapshot() call completed. ss: ", ss); // THIS NEVER APPEARS In The LOGS
       return ss;
    } catch (err) {
        console.log("!!! copy_snapshots() Throwing Error: ", err);
        throw Error(err); // TODO: throwing for now, but could this be handled better?
    }
}

exports.handler = async (event) => {
    
    return get_all_snapshots(src_account)
    .then(snapshots => {      
        copy_snapshot(snapshots.Snapshots[0].SnapshotId) // *** Add return here to fix ***
        .then(r =>{
            console.log("**new ss:", r); // THIS NEVER APPEARS IN THE LOGS
        })
        console.log("*** exports.handler() Ending");
     })
     .catch((err)=>{
         console.log("*** get_all_snapshots() Error: ",err);
     }); // End get_snapshots() 
};

标签: node.jsaws-lambdaasync-await

解决方案


推荐阅读