1

I tried to upload an image to aws s3 bucket using nodejs lambda function. But for the initial call no files are getting uploaded and when trying for the next time, previous file getting uploaded.

also it is not working as synchronously, even if we used inside async await.

async uploadAttachment(attachment, id) {
  try {
    let res = '';
    attachment.forEach(async (element, index) => {
      const encodedImage = element.base64;
      const fileTypeInfo = element.fileextType;
      const fileName = `${Math.floor(new Date() / 1000)}_${index + 1}.${fileTypeInfo}`;
      const decodedImage = Buffer.from(encodedImage, 'base64');
      const filePath = `${id}/${fileName}`;
      const params = {
        Body: decodedImage,
        Bucket: process.env.S3_FRF_BUCKET,
        Key: filePath
      };
      res = await s3.upload(params, () => {});
    });
    return res;
  } catch (e) {
    throw e;
  }
}

Any suggestions ?

2 Answers 2

1

.forEach on a regular array does not work with async/await like one would expect. Use a for..of instead.

for(let element of attachment) {
  // await actually waits here
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tried without using .foreach loop, but still had the upload issue. Like nth api call uploading n-1 api's file to s3.
Then I would suggest logging your inputs (and results) as it is processing, to get a better idea of what is occurring. Could try to help if I knew more.
Also have confusion like does it because of the lambda and s3 bucket communication. I have given ACL and policy as public for the bucket. But that also didn't help for the upload.
1

You need for loop as suggested before as well as adding promise in s3.upload

await s3.upload(params, () => {}).promise();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.