Home > Software engineering >  AWS Lambda - promise.all not working for s3.send DeleteObjectCommand
AWS Lambda - promise.all not working for s3.send DeleteObjectCommand

Time:07-30

I have a strange issue of Promise.all not working for s3.send for DeleteObjectCommand. I am using the same Promise.all for PutObject command and it is perfectly working fine.

Here are some of the snippets from my code base which makes things terrible. (Everything working perfectly fine in my development machine)


const removeObject = function (
  bucket: string,
  file: string
): Promise<DeleteObjectCommandOutput> {
  const s3 = getClient();
  const deleteObjectCommand = new DeleteObjectCommand({
    Bucket: bucket,
    Key: file,
  });
  return s3.send(deleteObjectCommand);
};

export const cleanUpThumbs = async (
  event: APIGatewayEvent | any,
  context: Context
): Promise<APIGatewayProxyResult> => {
  console.log(`Event: ${JSON.stringify(event, null, 2)}`);
  console.log(`Context: ${JSON.stringify(context, null, 2)}`);

  const destnBucketName =
    process.env.THUM_IMG_BUCKET_NAME ??
    "thumbs";
  const fileName = event?.Records[0]?.s3?.object?.key;
  const thumbSizes = getSizes();

  await Promise.all([
    thumbSizes.map(async (size) => {
      return removeObject(
        destnBucketName,
        `resized-${size.width}X${size.height}_${fileName}`
      );
    }),
  ]);

  return {
    statusCode: 200,
    body: JSON.stringify({ done: true }),
  };
};

When I changed the above Promise.all with below code, the code in the handler is working perfectly fine.

for (const size of thumbSizes) {
    await removeObject(
    destnBucketName,
    `resized-${size.width}X${size.height}_${fileName}`
  );
}

If someone faced the same issue in your AWS lambda environment, requesting your help.

CodePudding user response:

You're passing an array that contains a single nested array to Promise.all. You'll want to omit those […] brackets when already using .map():

await Promise.all(thumbSizes.map(size =>
  removeObject(
    destnBucketName,
    `resized-${size.width}X${size.height}_${fileName}`
  )
));
  • Related