'Can s3.getObject or s3.putObject be used in Promise.then() block?

I need to test if an object exists in an S3 bucket, if yes, I need to download the object, and if not, create the object. My code looks something like below:

let params = {
    Bucket: bucket,
    Key: fileName,        
};

const function async () => {
    await s3.headObject(params).promise()
    .then(() => {
        s3.getObject(params)
        .promise()
        .then(response => {
            console.log(response.Body.toISOString());
        });
    })
    .catch((err) => {
        if (err.code == "NotFound") {
            s3.putObject({
                Body: event,
                Bucket: bucket,
                Key: fileName,                  
            });
        }
    });
}

It doesn't seem to work, problem might be nesting an s3.getObject or s3.putObject call inside an then or catch block. I have tried prepending await before s3.getObject/s3.putObject, still no good.



Sources

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

Source: Stack Overflow

Solution Source