James Galley

Web application developer

PHP, Yii, MySQL, Node.js - JavaScript, HTML, CSS & SASS - Linux, AWS & serverless

How to use S3 getObject as a promise in Node.js

The Node.js AWS SDK documentation for S3 shows how to use S3 getObject and putObject with a callback function - but what if you want to use getObject with a promise in an async function?

It's actually pretty simple, as the Node.js SDK allows you to chain on the promise() function to promisify it.

const AWS = require("aws-sdk");
const s3 = new AWS.S3({
    apiVersion: "2006-03-01",
    region: "eu-west-2",
});

exports.handler = async function handler(event) {

    let s3Object = await s3.getObject({
        Bucket: "my-bucket",
        Key: "my-key"
    }).promise();

}

You can also chain on the then() and catch() functions

exports.handler = async function handler(event) {

    let s3Object = await s3.getObject({
        Bucket: "my-bucket",
        Key: "my-key"
    }).promise().then(() => {

    }).catch(() => {

    });

}

More about S3 and Node.js

AWS Node.js SDK docs for getObject: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property