0

I wrote the following code to upload files to amazon s3.

 var upload = async function() {

  var uploadURLs = []
  for (var i = 0; i < files.length; i++) {
    fs.readFile(filePath, (error, content) => {
      s3.putObject({
      Bucket: bucketName,
      Key: key,
      Body: content
    }, function(err, data){
  .....
  if (uploadCount == files.length - 1) {
  uploadURLs = allUrls;
  }
 }
}
return uploadURLs
}

The code is working fine but the returned array uploadURLs is empty where allUrls is not. Do you have an idea on how to solve the issue? Id I refer to this post I do not see any reason why this should not work.

j.doe
  • 4,559
  • 6
  • 20
  • 31

1 Answers1

1

You are returning a variable (in your case uploadURLs) that is not yet set because you are setting it inside an asyc callback function. In order for this to work, you should wait the operation to complete before returning it. The following declaration:

var upload = async function() {

does not help at all. You should do something like:

var upload = function() {
  return new Promise((success, fail) => {
    var uploadURLs = []
    for (var i = 0; i < files.length; i++) {
      fs.readFile(filePath, (error, content) => {
        if (error) {
          return fail(error);
        }
        s3.putObject({
          Bucket: bucketName,
          Key: key,
          Body: content
       }, function(err, data) {
         if (err) {
           return fail(err);
         }
         .....
         if (uploadCount == files.length - 1) {
           uploadURLs = allUrls;
           return success(uploadURLs);
         }
       }
     }
  });
}

Actually in this case uploadURLs may be completely unnecessary. Another thing is, that you should use async only if you are planning to have await inside your async function. Otherwise it's a waste.

logout
  • 621
  • 5
  • 13