I've got a Lambda that triggers a step function. I tried to upgrade it from node.js 10 to nod.je 12 and now it starts two Step functions (within two to three ms). Looks as it fires twice because I'm missing an async concept effect here. Can anyone explain this to me, please?
Old code (working)
'use strict';
var AWS = require('aws-sdk');
const s3 = new AWS.S3 ();
exports.handler = (event, context, callback) => {
event.SourceBucket = "bucket-A";
event.DestBucket = "bucket-B";
event.uriBase = decodeURIComponent(event.Records[0].s3.object.key);
event.uriBase = event.uriBase.substr(0,event.uriBase.lastIndexOf("/"));
event.uriBaseDel = event.uriBase + "/images";
event.Move = false;
//Get all img keys
const params = {
Bucket: event.SourceBucket,
Prefix: event.uriBase + "/images"
};
s3.listObjectsV2(params, function(err, data){
if(err){console.log(err)}else{
var result = data;
event.Keys = result.Contents.map(function(element){return(element.Key);});
// Start Step Function with Params
const stepfunctions = new AWS.StepFunctions();
const paramsb = {
stateMachineArn: 'my step function arn',
input: JSON.stringify(event),
};
stepfunctions.startExecution(paramsb, function(err, data) {
if (err) {callback(err, data);} // an error occurred
else {callback(null, data);} // successful response
});
}
});
};
New code (executes the Step function double)
'use strict';
var AWS = require('aws-sdk');
const s3 = new AWS.S3 ();
exports.handler = async (event) => {
event.SourceBucket = "bucket-A";
event.DestBucket = "bucket-B";
event.uriBase = decodeURIComponent(event.Records[0].s3.object.key);
event.uriBase = event.uriBase.substr(0,event.uriBase.lastIndexOf("/"));
event.uriBaseDel = event.uriBase + "/images";
event.Move = false;
//Get all img keys
const params = {
Bucket: event.SourceBucket,
Prefix: event.uriBase + "/images"
};
var result = await s3.listObjectsV2(params).promise();
event.Keys = result.Contents.map(function(element){return(element.Key);});
const stepfunctions = new AWS.StepFunctions();
const params2 = {
stateMachineArn: 'my step function arn',
input: JSON.stringify(event)
};
stepfunctions.startExecution(params2, function(err, data) {
if (err) {return(err, data);} // an error occurred
else {return(null, data);} // successful response
});
};
callbackbefore thestartExecutionwas done. Your new code ignores the result ofstartExecution, and immediately resolves the promise returned by theasyncfunction. Why this would lead to a double execution I cannot say.