'await s3.getObject(params) returns object, but adding .promise() does not

I am trying to simply pull an image from an S3 bucket inside of an aws-lambda script that I wrote in Node.

From all the examples I see, people do:

const params = {
  Bucket: event.bucket,
  Key: event.prefix,
};


console.log('Calling getObject'); // This gets hit
const data = (await (s3.getObject(params).promise())).Body.toString('utf-8')
console.log({ data }); // This NEVER gets hit 😤

However, when I do it without the .promise() like:

const res = await s3.getObject(params);
console.log(res);

I do get a response. How can I pull an image or buffered object using s3.getObject()?



Solution 1:[1]

You could try it with something like:


  async function getObj(params) {
    const {
      Bucket,
      Key,
    } = params;

    const getObjectPromise = () => new Promise((resolve, reject) => {
      try {
        const data = s3.getObject(params);
        resolve(data);
      } catch (error) {
        reject(error);
      }
    });

    const response = await getObjectPromise();
    // Do Something with response
  }

EDIT:

If I'm not mistaken, the newer versions of S3 return a Readable stream. If so, you'll have to do:


...

    const response = await getObjectPromise();
  
    const data: string[] = [];
    for await (const chunk of response.Body) {
      data.push(chunk.toString());
    }

    return data.join('');

Solution 2:[2]

It turns out, I just had to hit the "Test" button multiple times.

Such a terrible experience.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 dsomel21