Search code examples
angularamazon-s3es6-promiseangular-promise

Angular, Promises: Don't return promise till batch has completed


TL;DR I have to read 3 files from S3. I'm using Promises, and I don't want them to "return" until they've all returned

I have code I use to read from S3 in an Angular setup. It looks kind of like this:

return new Promise((resolve, reject) => {
  const s3 = new AWS.S3({
    apiVersion: '2006-03-01',
    params: {
      Bucket: this._bucketKey,
      Key: this._someKey
    }
  });
  s3.config.update({credentials: AWS.config.credentials});
  s3.getObject((err, data) => {
    ...
     }
   });
 });

}

What I would like to do, is pass a list of S3 keys to the function, and then have it return after the data for all 3 calls, as this read is wrapped in a function.

readMultipleKeys(s3Keys:[]): Promise<any> {
    data.forEach( value => {
       "read value key from S3"
   });

   // resolve after all the array items in data have been requested and returned
}

Any help is greatly appreciated


Solution

  • Let's say you have a method called `getFileFromAws()' that takes in the S3key and performs the http call to get the file from S3 storage. Your expected solution will look like below.

    getFileFromAws(s3Key) {
      // Perform the HTTP call to get the file like below
      // return this.http.get(url, httpOptions).toPromise();
    }
    
    async readMultipleKeys(s3Keys:[]) {
      let files = await Promise.all(s3Keys.map(key => getFileFromAws(key)));
      console.log(files);
      // now the files array contains 3 files if you passed 3 keys to this method
    
      // Perform your logic
    }
    

    I have created a demo Stackblitz app to show the Promise.all method.