1

I am trying to create a function that returns back either the error data from AWS or the { ETag: '"74..."' } data response from the callback. This code currently will write my buffer file to the the s3 bucket. But I want to return my etag number or the error data back from the function but I keep getting undefined. Any help would be appreciated.

function aws(file, name) {
  var s3 = new AWS.S3();
  s3.putObject({
    Bucket: 'Bucket-Name',
    ACL: 'public-read',
    Key: name,
    Body: file
  }, function(err, data) {
    if (err) {
      console.log('Something went wrong')
      return err;
    } else {
      console.log('Successfully uploaded image');
      console.log(data);
      return data;
    }
  });
}

var response = aws(buffer, 'file.png');
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Jul 21 '17 at 08:07

1 Answers1

2

Solved my problem with a Promise. Hope this helps someone else someday :)

const aws = function (file, name) {

  return new Promise((resolve, reject) => {
    let s3 = new AWS.S3();
    s3.putObject({
      Bucket: 'Bucket-Name',
      ACL: 'public-read',
      Key: name,
      Body: file
    }, function (err, data) {
      if (err) {
        console.log('Something went wrong')
        reject(err);
      } else {
        console.log('Successfully uploaded image');
        resolve(data);
      }
    });
  });

}

aws(buffer, 'file.png')
    .then(response => {
        res.set({ 'Content-Type': 'application/json' });
        res.status(200);
        res.send(response);
    })
    .catch(console.error);