0

I have a script in Typescript that works for reading files from S3 but now want to read 2 files, concatinate the output of both and then print as a total_string.

var total_string = '';
var files = ['file1.txt', 'file2.txt'];

for (var file of files) {
  var s3_params = {
    Bucket: 'bucket1', 
    Key: file
  }

  s3.getObject(s3_params, function(err, data) {
    if (err) {
      console.log("\nError!!!\n");
      console.log(err, err.stack); 
    }
    else {
      console.log("Data in a file:", data); 
      let objectData = data.Body.toString('utf-8');
      console.log("objectData:\n", objectData);  
      total_string = total_string.concat(objectData);
    }
  });
}

console.log(total_string);

Currently - total_string is printing before other ones are executed so need to convert above code into Promise I believe..

Joe
  • 11,983
  • 31
  • 109
  • 183
  • 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) – marekful Feb 25 '19 at 15:21
  • Yes, promises sound like a good idea. Should become something like `Promise.all(filenames.map(readFile)).then(concat).then(writeOutputFile)` – Bergi Feb 25 '19 at 15:33
  • How do you pass values (content of each file) from one function (readFile) to another (writeOutputFile)? – Joe Feb 25 '19 at 17:14

0 Answers0