summerNight
summerNight

Reputation: 1496

Calling a function that contains a promise from another function

I am trying to learn how to use promises in NodeJs and I am using the AWS-SDK library to access an S3 object. My goal is to call the readFromS3() function from within the init() function and print out the contents of the file. However, I am not getting the results I want as shown below by the first console.log statement inside the init(). I understand that the promise is not complete and wanted your suggestions on how I can block execution until the news object is NOT null ??

const AWS = require('aws-sdk');

const S3 = new AWS.S3({});

const CONFIG = {
  init() {
    const news = CONFIG.readFromS3();
    console.log('These are the file contents ' + JSON.stringify(news));
    console.log('THIS IS THE END. This should only print after news have been read from S3');
  },

  readFromS3() {
    // set parameters for reading S3 files
    const options = {
      Bucket: 'my-bucket',
      Key: 'myFile.txt'
    };

    // create a promise to read from S3
    const readS3Promise = S3.getObject(options).promise();

    // start reading from s3
    readS3Promise
      .then(function(data) {
        return JSON.parse(data.Body);

        });
      })
      .catch(function(error) {
        console.log('ERROR: Cannot read from S3');
        throw error;
      });
  }
};

CONFIG.init();

However, My output currently is like this unfortunately:

These are the SPECS undefined
THIS IS THE END. This should only print after news have been read from S3
{... // JSON data from S3 printed out

Upvotes: 0

Views: 105

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

You need to return your promise from read method and await that call inside init function so you can get output. something like this

const AWS = require('aws-sdk');

const S3 = new AWS.S3({});

const CONFIG = {
  async init() {
    const news = await CONFIG.readFromS3();
    console.log('These are the file contents ' + JSON.stringify(news));
    console.log('THIS IS THE END. This should only print after news have been read from S3');
  },

  readFromS3() {
    // set parameters for reading S3 files
    const options = {
      Bucket: 'my-bucket',
      Key: 'myFile.txt'
    };

    // create a promise to read from S3
    const readS3Promise = S3.getObject(options).promise();

    // start reading from s3
    return readS3Promise
      .then(function(data) {
        return JSON.parse(data.Body);

        });
      })
      .catch(function(error) {
        console.log('ERROR: Cannot read from S3');
        throw error;
      });
  }
};

CONFIG.init();

Upvotes: 1

Related Questions